4 回答

TA貢獻1836條經驗 獲得超13個贊
Txt 文檔無法保存列表元素,但您可以將列表作為 JavaScript 對象存儲在 JSON 中。有關如何執行此操作的信息,請轉到此處:https://www.w3schools.com/python/python_json.asp。實現此目的的另一種方法是將名稱逐個打印到txt文檔中,然后使用read函數讀取它并將其放回列表中。

TA貢獻1770條經驗 獲得超3個贊
您可以將每個列表項保存到新行,然后在讀取時重新創建列表。
寫入文件:
# define list of places
places = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']
with open('listfile.txt', 'w') as filehandle:
for listitem in places:
filehandle.write('%s\n' % listitem)
從文件讀取:
# define an empty list
places = []
# open file and read the content in a list
with open('listfile.txt', 'r') as filehandle:
for line in filehandle:
# remove linebreak which is the last character of the string
currentPlace = line[:-1]
# add item to the list
places.append(currentPlace)

TA貢獻1862條經驗 獲得超7個贊
將保存代碼更改為以下內容
text_file = open("/Users/xxxxxx/Desktop/names.txt", "w")
text_file.writelines(list)
text_file.close()
print("Your list has been saved!")
這會將每個名稱保存在新行上。writelines 函數會將列表中的每個字符串寫入文件中的新行。當您想從文件中加載它時,您可以按照現在的工作方式進行,也可以執行以下操作。
testList=[]
with open("/Users/xxxxxxx/Desktop/names.txt") as f:
testList = f.readlines()
添加回答
舉報