我编写了以下代码,目的是将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())
我该怎么做?
答案 0 :(得分:10)
您正在寻找shutil.copyfileobj()
。
答案 1 :(得分:4)
您正在拨打a_file.read()
两次。它第一次读取整个文件,但在打开xyz.txt
后尝试再次执行该文件时丢失了 - 因此没有任何内容写入该文件。试试这个来避免这个问题:
import locale
with open('/home/chirag/abc.txt','r',
encoding=locale.getpreferredencoding()) as a_file:
a_content = a_file.read() # only do once
print(a_content)
# print(a_file.closed) # not really useful information
with open('/home/chirag/xyz.txt','w',
encoding=locale.getpreferredencoding()) as b_file:
b_file.write(a_content)
with open('/home/chirag/xyz.txt','r',
encoding=locale.getpreferredencoding()) as b_file:
print(b_file.read())
答案 2 :(得分:2)
要将abc.txt的内容复制到xyz.txt,您可以使用shutil.copyfile()
:
import shutil
shutil.copyfile("abc.txt", "xyz.txt")