Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python 3将一个文件的内容复制到另一个文件中_Python_Python 3.x_File Handling - Fatal编程技术网

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

使用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())

我编写了以下代码,打算将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())
    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,可以使用: