我有一个变量all = [],它存储了一个附加的项目列表,如下所示:
qwe 1qw78 12 qqq ss7 shhs bs77 sghs 7shsb qwe 1qw78 12 qqq ss7 shhs bs77 sghs 7shsb
我尝试将制表符分隔格式的项目输出为3列到文件中,如下所示:
输出需要:
qwe 1qw78 12
qqq ss7 shhs
bs77 sghs 7shsb
我不确定如何做到这一点,但我的尝试如下:
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)
任何建议都将受到赞赏。
由于
答案 0 :(得分:1)
如果all是一个列表,则以下内容将起作用,将所有内容替换为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")
如果您的问题中的每一行都是分开的每一行:
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")
如果你在每一行都有一个单词,那么modulo和enumerate会做你想要的:
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")