<分区>
我有 2 个文本文件,例如 ['file1.txt', 'file2.txt']。我想编写一个 Python 脚本将这些文件连接成一个新文件,使用 open() 等基本函数打开每个文件,通过调用 f.readline() 逐行读取,然后使用 f 将每一行写入新文件。写()。我是 python 文件处理编程的新手。有人可以帮我解决这个问题吗?
标签 python
<分区>
我有 2 个文本文件,例如 ['file1.txt', 'file2.txt']。我想编写一个 Python 脚本将这些文件连接成一个新文件,使用 open() 等基本函数打开每个文件,通过调用 f.readline() 逐行读取,然后使用 f 将每一行写入新文件。写()。我是 python 文件处理编程的新手。有人可以帮我解决这个问题吗?
最佳答案
响应是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)
您需要的(根据评论)是一个只有两行的文件。第一行是第一个文件的内容(没有换行),第二行是第二个文件的内容。因此,如果您的文件很小(每个文件小于 ~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)
关于python - 将多个文件合并到一个新文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313941/