我已经制作了一个嵌套列表并且它可以打印我需要将其写入文本文件但是不明白如何尝试进行研究而没有找到任何人的帮助吗?
nestedList = [["Judge","01","02","03","04","05"],
["Couple A","10","06","03","04","05"]]
file = open("NewFile.txt","w")
for item in nestedList:
print(":",item[0]," "*(8-len(item[0])),":",
item[1]," "*(0-len(item[1])),":",
item[2]," "*(0-len(item[2])),":",
item[3]," "*(0-len(item[3])),":",
item[4]," "*(0-len(item[4])),":",
item[5]," "*(0-len(item[5])),":")
file.close()
编辑:
我已将代码更改为:
nestedList = [["Judge","01","02","03","04","05"],
["Couple A","10","06","03","04","05"]]
with open("NewFile.txt",'w') as outfile:
for item in nestedList:
(":",item[0]," "*(8-len(item[0])),":",
item[1]," "*(0-len(item[1])),":",
item[2]," "*(0-len(item[2])),":",
item[3]," "*(0-len(item[3])),":",
item[4]," "*(0-len(item[4])),":",
item[5]," "*(0-len(item[5])),":")
outfile.close()
答案 0 :(得分:0)
以下代码可以帮助您写入文件。不确定预期的输出是什么。您可以修改write语句以打印任何您喜欢的内容。
nestedList = [["Judge","01","02","03","04","05"],
["Couple A","10","06","03","04","05"]]
with open("myfile.txt",'w') as outfile:
for i in nestedList:
outfile.write(str(i))
更新: 以下代码写入文件。 (根据需要在打印后写下所有内容)
,
不被接受,因为它认为是多个参数。相反,+
用于连接字符串,然后可以编写。
nestedList = [["Judge","01","02","03","04","05"],
["Couple A","10","06","03","04","05"]]
with open("myfile.txt",'w') as outfile:
for item in nestedList:
outfile.write(":"+item[0] + " "*(8-len(item[0]))+":"+
item[1]+" "*(0-len(item[1]))+":"+
item[2]+" "*(0-len(item[2]))+":"+
item[3]+" "*(0-len(item[3]))+":"+
item[4]+" "*(0-len(item[4]))+":"+
item[5]+" "*(0-len(item[5]))+":")
更新2:
如果您想格式化代码,您可能需要查看格式,但这是一个让它看起来相似的示例
nestedList = [["Judge","01","02","03","04","05"],
["Couple A","10","06","03","04","05"]]
with open("myfile.txt",'w') as outfile:
for item in nestedList:
outfile.write("\n:\t"+item[0] + " "*(8-len(item[0]))+":"+
item[1]+" \t"*(0-len(item[1]))+":\t"+
item[4]+" \t"*(0-len(item[4]))+":\t"+
item[2]+" \t"*(0-len(item[2]))+":\t"+
item[3]+" \t"*(0-len(item[3]))+":\t"+
item[5]+" \t"*(0-len(item[5]))+":\t")