从文件spli获取字符串

2024-04-26 07:36:20 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我有个档案txt.txt文件你知道吗

item1, item2

在代码中我想做一个对象

Object(item1, item2)

我不知道如何按我需要的方式从文件中获取item1item2。我尝试使用file = open("txt.txt").read()字符串并以某种方式拆分它,但失败了。尝试将它放入一个列表,结果是在item1item2字符串中有[和其他内容。你知道吗


Tags: 文件对象字符串代码txt内容列表read
1条回答
网友
1楼 · 发布于 2024-04-26 07:36:20

这个答案创建了一个对象列表,对象是通过遍历文件中的每一行并将每一行拆分为两个项目,然后使用它们来构造对象。你知道吗

objects = [] #the object list
with open("path/to/file") as reader: #opens the file
    for line in reader: #iterates the lines
        objects.append(Object(*line.strip().split(", "))) #appends the objects to the list

关于最后一行的更多细节,可以这样打开:

parts = line.strip.split(", ") #each item in the line
obj = Object(parts[0], parts[1]) #like doing Objects(item1, item2) from the line.
objects.append(obj) #add the object to the list

相关问题 更多 >