4 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
Txt 文檔無(wú)法保存列表元素,但您可以將列表作為 JavaScript 對(duì)象存儲(chǔ)在 JSON 中。有關(guān)如何執(zhí)行此操作的信息,請(qǐng)轉(zhuǎn)到此處:https://www.w3schools.com/python/python_json.asp。實(shí)現(xiàn)此目的的另一種方法是將名稱逐個(gè)打印到txt文檔中,然后使用read函數(shù)讀取它并將其放回列表中。

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以將每個(gè)列表項(xiàng)保存到新行,然后在讀取時(shí)重新創(chuàng)建列表。
寫入文件:
# 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)
從文件讀?。?/p>
# 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貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
將保存代碼更改為以下內(nèi)容
text_file = open("/Users/xxxxxx/Desktop/names.txt", "w")
text_file.writelines(list)
text_file.close()
print("Your list has been saved!")
這會(huì)將每個(gè)名稱保存在新行上。writelines 函數(shù)會(huì)將列表中的每個(gè)字符串寫入文件中的新行。當(dāng)您想從文件中加載它時(shí),您可以按照現(xiàn)在的工作方式進(jìn)行,也可以執(zhí)行以下操作。
testList=[]
with open("/Users/xxxxxxx/Desktop/names.txt") as f:
testList = f.readlines()
添加回答
舉報(bào)