[英]How to combine several text files into one file?
I want to combine several text files into one output files. 我想将几个文本文件合并为一个输出文件。 my original code is to download 100 text files then each time I filter the text from several words and the write it to the output file.
我的原始代码是下载100个文本文件,然后每次我从几个单词中过滤文本并将其写入输出文件时。
Here is part of my code that suppose to combine the new text with the output text. 这是我的代码的一部分,该代码假定将新文本与输出文本组合在一起。 The result each time overwrite the output file, delete the previous content and add the new text.
每次结果都会覆盖输出文件,删除先前的内容并添加新的文本。
import fileinput
import glob
urls = ['f1.txt', 'f2.txt','f3.txt']
N =0;
print "read files"
for url in urls:
read_files = glob.glob(urls[N])
with open("result.txt", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
outfile.write(infile.read())
N+=1
and I tried this also 我也尝试过
import fileinput
import glob
urls = ['f1.txt', 'f2.txt','f3.txt']
N =0;
print "read files"
for url in urls:
file_list = glob.glob(urls[N])
with open('result-1.txt', 'w') as file:
input_lines = fileinput.input(file_list)
file.writelines(input_lines)
N+=1
Is there any suggestions? 有什么建议吗? I need to concatenate/combine approximately 100 text files into one .txt file In sequence manner.
我需要按顺序将大约100个文本文件串联/组合为一个.txt文件。 (Each time I read one file and add it to the result.txt)
(每次我读取一个文件并将其添加到result.txt中)
The problem is that you are re-opening the output file on each loop iteration which will cause it to overwrite -- unless you explicitly open it in append mode. 问题是您将在每次循环迭代时重新打开输出文件,这将导致其覆盖-除非您在追加模式下显式打开它。
The glob logic is also unnecessary when you already know the filename. 当您已经知道文件名时,也不需要使用全局逻辑。
Try this instead: 尝试以下方法:
with open("result.txt", "wb") as outfile:
for url in urls:
with open(url, "rb") as infile:
outfile.write(infile.read())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.