我正在尝试使用zip函数将多个文本文件连接在一起,但我一直收到错误TypeError: coercing to Unicode: need string or buffer, generator found
这是我的代码,
filepaths = ['file1.txt', 'file2.txt', 'file3.txt']
with open('op.txt', 'w') as f:
temp = zip(*[open(fpath for fpath in filepaths)])
for lines in temp:
outfile.write('\t'.join(line.strip() for line in lines) + '\n')
请帮我解决这个错误,我不熟悉使用zip& amp;蟒
答案 0 :(得分:0)
我认为你打算打开每个文件,而不是生成器。您是否也想使用f.write
代替outfile.write
?
这对我有用:
filepaths = ['file1.txt', 'file2.txt', 'file3.txt']
with open('op.txt', 'w') as f:
temp = zip(*[open(fpath) for fpath in filepaths])
for lines in temp:
f.write('\t'.join(line.strip() for line in lines) + '\n')
另请注意,这只会打印最短文件长度的行,因为这是zip
的行为方式。如果文件的长度不同,并且您希望查看所有其他行,则需要采用不同的策略,如下所示:
from itertools import izip_longest
filepaths = ['file1.txt', 'file2.txt', 'file3.txt']
with open('op.txt', 'w') as f:
temp = izip_longest(*[open(fpath) for fpath in filepaths])
for lines in temp:
f.write('\t'.join(line.strip() for line in lines if line) + '\n')