i have made a nested list and it works a print i need to write it to a text file but dont understand how to and have tried to do research and not found anything anyone help?
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()
Edited:
I've changed code to this:
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()
The following code can help you write to file. Not sure what the expected output is. You can modify the write statement to print anything you like.
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))
UPDATE: The following code below writes to the file. (Writes everything after the print as wanted)
,
is not accepted as it sees as multiple arguments. Instead +
is used to concatenate strings, which then can be written.
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]))+":")
UPDATE 2:
If you want to format the code, you might want to look into formatting but here is a an example to make it look similar
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.