基本的に私はファイルtxt.txtを持っています
item1, item2
コードでオブジェクトを作成したい
Object(item1, item2)
そして、必要な方法でファイルを取得item1
および取得する方法がわかりません。item2
文字列を使用しfile = open("txt.txt").read()
て何とか分割しようとしましたが、失敗しました。それをリストに入れようとしたところ、文字列[
やその他のものがitem1
ありitem2
ます。
この回答はオブジェクトのリストを作成します。オブジェクトは、ファイル内の各行を繰り返し処理し、各行を両方の項目に分割し、それらを使用してオブジェクトを構築することによって作成されます。
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