使用Python 3将一个文件的内容复制到另一个文件中
我编写了以下代码,打算将abc.txt的内容复制到另一个文件xyz.txt中 但是语句使用Python 3将一个文件的内容复制到另一个文件中,python,python-3.x,file-handling,Python,Python 3.x,File Handling,我编写了以下代码,打算将abc.txt的内容复制到另一个文件xyz.txt中 但是语句b\u file.write(a\u file.read())似乎没有按预期工作。如果我用字符串替换_file.read(),它(字符串)就会被打印出来 import locale with open('/home/chirag/abc.txt','r', encoding = locale.getpreferredencoding()) as a_file: print(a_file.read())
b\u file.write(a\u file.read())
似乎没有按预期工作。如果我用字符串替换_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())
我该怎么做呢?您正在寻找。您正在寻找。您正在调用
一个文件。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())
您调用了两次
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())
要将abc.txt的内容复制到xyz.txt,可以使用:
要将abc.txt的内容复制到xyz.txt,可以使用: