Python 将多个文件合并到一个新文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20313941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
merging multiple files in to a new file
提问by Shraddha
I have 2 text files, like ['file1.txt', 'file2.txt']. I want to write a Python script to concatenate these files into a new file, using basic functions like open() to open each file, read line by line by calling f.readline(), and write each line into that new file using f.write(). I am new to file handling programming in python. Can someone help me with this?
我有 2 个文本文件,例如 ['file1.txt', 'file2.txt']。我想编写一个 Python 脚本来将这些文件连接到一个新文件中,使用 open() 等基本函数打开每个文件,通过调用 f.readline() 逐行读取,然后使用 f 将每一行写入该新文件。写()。我是 Python 中文件处理编程的新手。有人可以帮我弄这个吗?
回答by Maxime Lorant
The response is already here:
回应已经在这里:
filenames = ['file1.txt', 'file2.txt', ...]
with open('result.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
Flat line solution
扁线解决方案
What you need (according to comments), is a file with only 2 lines. On the first line, the content of the first file (without break lines) and on the second line, the second file. So, if your files are small (less than ~1MB each, after it can take a lot of memory...)
您需要(根据评论)是一个只有 2 行的文件。第一行是第一个文件的内容(不带换行符),第二行是第二个文件的内容。因此,如果您的文件很小(每个文件小于 ~1MB,之后可能会占用大量内存......)
filenames = ['file1.txt', 'file2.txt', ...]
with open('result.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
content = infile.read().replace('\n', '')
outfile.write(content)
回答by Hardmath123
f1 = open("file1.txt")
f1_contents = f1.read()
f1.close()
f2 = open("file2.txt")
f2_contents = f2.read()
f2.close()
f3 = open("concatenated.txt", "w") # open in `w` mode to write
f3.write(f1_contents + f2_contents) # concatenate the contents
f3.close()
If you're not particular on Python, the UNIX catcommand does exactly that: concatenates the contents of multiple files.
如果您对 Python 不是特别感兴趣,那么 UNIXcat命令就是这样做的:连接多个文件的内容。
If you want a line break between the two files, change the second-to-last line to have f1_contents + "\n" + f2_contents. (\nmeans new line).
如果要在两个文件之间换行,请将倒数第二行更改为f1_contents + "\n" + f2_contents. (\n表示新行)。

