1

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

我该怎么做?

4

3 回答 3

10

你正在寻找shutil.copyfileobj().

于 2013-02-09T17:08:29.593 回答
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())
于 2013-02-09T19:44:10.417 回答
2

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

import shutil

shutil.copyfile("abc.txt", "xyz.txt")
于 2013-02-10T00:05:49.880 回答