方法一
將列表寫入txt文件中
如下代碼所示
a是一段二維列表,需要把它寫入一個(gè)txt文件中。
a=[['1','9'],['2','5'],['3','3'],['2','4'],['4','3'],['1','8'],['1','9']]
t=''
with open ('N_a.txt','w') as q:
for i in a:
for e in range(len(a[0])):
t=t+str(i[e])+' '
q.write(t.strip(' '))
q.write('\n')
t=''
方法二
數(shù)據(jù):
u = [['mov', 'push', 'push', 'call', 'push', 'push', 'push', 'call'],['pop', 'push', 'call', 'pop', 'retn', 'mov', 'push', 'call', 'push'],['push', 'push', 'call', 'pop', 'call', 'pop', 'retn', 'mov', 'push'], ['lea', 'push', 'call', 'test', 'jnz', 'push', 'push']]
1
代碼:
def text_save(filename, data):#filename為寫入txt文件的路徑,data為要寫入數(shù)據(jù)列表.
? ? file = open(filename,'a')
? ? for i in range(len(data)):
? ? ? ? s = str(data[i]).replace('[','').replace(']','')#去除[],這兩行按數(shù)據(jù)不同,可以選擇
? ? ? ? s = s.replace("'",'').replace(',','') +'\n' ? #去除單引號,逗號,每行末尾追加換行符
? ? ? ? file.write(s)
? ? file.close()
? ? print("保存文件成功")?
text_save('N_aa.txt',u)
在已有內(nèi)容的txt文件的后面,再存入新的內(nèi)容
只需將之間的打開方式由file = open(filename, 'w')改為file = open(filename, 'a')即可。
# 將操作碼保存為txt文件
def text_save(filename, data): ?# filename為寫入txt文件的路徑,data為要寫入數(shù)據(jù)列表.
? ? file = open(filename, 'a')
? ? for i in range(len(data)):
? ? ? ? s = str(data[i]).replace('[', '').replace(']', '')#去除[],這兩行按數(shù)據(jù)不同,可以選擇
? ? ? ? s = s.replace("'", '').replace(',', '') + '\n' #去除單引號,逗號,每行末尾追加換行符
? ? ? ? file.write(s)
? ? file.close()
? ? print("保存文件成功")
ops = [['i','love','china'],['happy','birthday']]
文章來源:http://www.zghlxwxcb.cn/news/detail-695273.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-695273.html
到了這里,關(guān)于python list列表寫入txt文檔的多種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!