合并文件是 Python 中一项常见的文件处理任务。在本文中,我们将探讨如何使用多种方法将两个文件合并到第三个文件中。
> 注意: 请确保 file1.txt 和 file2.txt 存在于与您的 Python 脚本相同的目录中。
示例文本文件:
file1.txt
!Python-file-handling-file1 file2.txt !Python-file-handling-file2
使用 shutil.copyfileobj()
shutil.copyfileobj() 可以高效地将内容从一个文件对象复制到另一个文件对象,而无需将整个文件加载到内存中。这对于大文件来说是非常理想的选择。
Python
CODEBLOCK_d0580ca7
输出 (merged_file.txt)
> This is the content from file1 .
> Hello There.
> This is in file1
> Hello Geeks
> This is in file2
解释:
- with open(‘merged_file.txt‘, ‘w‘) as outfile: 以二进制写入模式打开输出文件(注:此处英文原文解释可能有误,‘w‘通常为文本模式,‘wb‘才是二进制,但依原文翻译)。
- for filename in [‘file1.txt‘, ‘file2.txt‘]: 遍历需要合并的文件。
- outfile.write(infile.read()): 将内容原样写入输出文件。
使用 os 模块
此方法使用 os 模块进行基本的文件处理,逐行读取文件并将其内容写入单个文件。这是一种内存高效的方法,适用于大文件。
Python
CODEBLOCK_c1470d93
输出
> This is the content from file1 .
> Hello There.
> This is in file1
> Hello Geeks
> This is in file2
解释:
- for filename in [‘file1.txt‘, ‘file2.txt‘]: 遍历需要合并的输入文件。
- content = infile.read(): 读取输入文件的全部内容。
- if not content.endswith(‘
‘): 检查最后一行是否以换行符结尾。
- outfile.write(‘
‘): 仅在缺少换行符时添加换行,以便下一个文件从新行开始。
使用 For 循环
此方法通过循环遍历文件名列表,将其内容写入新文件来合并文件。这种方法简单、易读且对初学者友好,非常适合中小型文件。
Python
CODEBLOCK_e82a1332
输出
> This is the content from file1.
> Hello There.
> This is in file1
> Hello Geeks
> This is in file2
解释:
- filenames = [‘file1.txt‘, ‘file2.txt‘]: 存储要合并的文件名。
- for name in filenames: 循环遍历每个输入文件。
- with open(name) as infile: 以读取模式打开每个文件。
- outfile.write(infile.read()): 读取整个文件内容并将其写入 file3.txt。
基础方法
这种方法将两个文件的全部内容读入字符串,将它们连接起来,然后将组合后的字符串写入一个新文件。
Python
CODEBLOCK_ddfe267e
输出
> This is the content from file1.
> Hello There.
> This is in file1
> Hello Geeks
> This is in file2
解释:
- data1 = fp.read(): 将 file1.txt 的全部内容读入字符串 data1。
- with open(‘file2.txt‘) as fp: 以读取模式打开 file2.txt。
- data2 = fp.read(): 将 file2.txt 的全部内容读入字符串 data2。