【问题标题】:Copy contents of one file into other using Python 3使用 Python 3 将一个文件的内容复制到另一个文件中
【发布时间】:2013-02-09 17:07:14
【问题描述】:

我编写了以下代码,目的是将 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())

我该怎么做?

【问题讨论】:

    标签: python python-3.x file-handling


    【解决方案1】:

    您正在寻找shutil.copyfileobj()

    【讨论】:

      【解决方案2】:

      您拨打了两次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())
      

      【讨论】:

        【解决方案3】:

        要将 abc.txt 的内容复制到 xyz.txt,可以使用shutil.copyfile()

        import shutil
        
        shutil.copyfile("abc.txt", "xyz.txt")
        

        【讨论】:

          猜你喜欢
          • 2021-09-02
          • 2015-07-17
          • 2016-03-30
          • 1970-01-01
          • 1970-01-01
          • 2018-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多