I have a variable,all=[], which stores an appended list of items as follows:
qwe 1qw78 12 qqq ss7 shhs bs77 sghs 7shsb qwe 1qw78 12 qqq ss7 shhs bs77 sghs 7shsb
I tried to ouput the items in a tab-delimited format as 3 columns into a file as follows:
output wanted:
qwe 1qw78 12
qqq ss7 shhs
bs77 sghs 7shsb
I was not exactly sure how to do this, but my attempt is below:
all=[]
with open("file.txt", "r") as input, open("output.txt","w") as outfile:
for line in input:
line=line.rstrip()
all.append(line)
for i,item in enumerate(all):
for i in range(3):
outfile.write("%s \t" %all)
Any advice will be appreciated.
Thanks
If all is a list the following will work, replacing all with lst:
grouped = (lst[i:i+3] for i in range(0,len(lst),3))
with open("output.txt","w") as f:
for tup in grouped:
f.write("\t".join(tup)+"\n")
If each line is as in your question just split each line:
with open("file.txt", "r") as input, open("output.txt","w") as outfile:
for line in input:
line = line.rstrip().split()
grouped = (lst[i:i+3] for i in range(0,len(lst),3))
for tup in grouped:
outfile.write("\t".join(tup)+"\n")
If you have a word on each line then modulo and enumerate will do what you want:
with open("input.txt", "r") as inp, open("output.txt","w") as outfile:
for ind, line in enumerate(inp,1):
if ind % 3 == 0:
outfile.write(line.rstrip()+"\n")
else:
outfile.write(line.rstrip() + "\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.