方法一
将列表写入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
在已有内容的txt文件的后面,再存入新的内容
只需将之间的打开方式由file = open(filename, 'w')
改为file = open(filename, 'a')
即可。
# 将操作码保存为txt文件
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("保存文件成功")
ops = [['i','love','china'],['happy','birthday']]