python 将列表里面的内容写入到txt文件中
程序员文章站
2024-03-22 19:22:16
...
方法一
将列表写入txt文件中
如下代码所示
a是一段二维列表,需要把它写入一个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=''
结果
参考链接:https://blog.csdn.net/longling0/article/details/107022150/
数据: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’]]
代码:
t=''
with open ('N_a.txt','w') as q:
for i in u:
# print(i) #i为['1','9'] ['2','5']
for e in range(len(i)):
# print(a[0]) #a[0]为['1','9']
# print(e) #e为0、1
t=t+str(i[e])+' '
q.write(t.strip(' '))
q.write('\n')
t=''
结果
方法二
数据:
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']]
代码:
def text_save(filename, data):#filename为写入txt文件的路径,data为要写入数据列表.
file = open(filename,'a')
for i in range(len(data)):
s = str(data[i]).replace('[','').replace(']','')#去除[],这两行按数据不同,可以选择
s = s.replace("'",'').replace(',','') +'\n' #去除单引号,逗号,每行末尾追加换行符
file.write(s)
file.close()
print("保存文件成功")
text_save('N_aa.txt',u)
结果
参考链接:https://blog.csdn.net/u010513327/article/details/80889846?utm_medium=distribute.pc_relevant.none-task-blog-title-2&spm=1001.2101.3001.4242