我在文件夹中有一些.txt文件。我需要在一个.txt文件中收集他们的内容。我正在使用Python并尝试:
import os
rootdir = "\\path_to_folder\\"
for files in os.walk(rootdir):
with open ("out.txt", 'w') as outfile:
for fname in files:
with open(fname) as infile:
for line in infile:
outfile.write(line)
但没有奏效。生成'out.txt'但代码永远不会结束。有什么建议?提前谢谢。
答案 0 :(得分:2)
os.walk
返回元组,而不是文件名:
with open ("out.txt", 'w') as outfile:
for root, dirs, files in os.walk(rootdir):
for fname in files:
with open(os.path.join(root, fname)) as infile:
for line in infile:
outfile.write(line)
此外,您应该在开头打开outfile,而不是在每个循环中打开。
答案 1 :(得分:0)
这解决了我的问题。生成的'out.txt'文件只有151KB。
file_list = os.listdir("\\path_to_folder\\")
with open('out.txt', 'a+') as outfile:
for fname in file_list:
with open(fname) as infile:
outfile.write(infile.read())
谢谢大家。