Skip to main content
 首页 » 编程设计

python之使用 Python 3 将一个文件的内容复制到另一个文件中

2025年05月04日12duanxz

我写了下面的一段代码,目的是将 abc.txt 的内容复制到另一个文件 xyz.txt

但是声明 b_file.write(a_file.read()) 似乎没有按预期工作。如果我用一些字符串替换 a_file.read(),它(字符串)就会被打印出来。

import locale 
with open('/home/chirag/abc.txt','r', encoding = locale.getpreferredencoding()) as a_file: 
    print(a_file.read()) 
    print(a_file.closed) 
 
    with open('/home/chirag/xyz.txt','w', encoding = locale.getpreferredencoding()) as b_file: 
        b_file.write(a_file.read()) 
 
    with open('/home/chirag/xyz.txt','r', encoding = locale.getpreferredencoding()) as b_file: 
        print(b_file.read()) 

我该怎么做?

请您参考如下方法:

您正在寻找 shutil.copyfileobj() .