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()2回電話しています。初めてファイル全体を読み取るが、開いた後に再度読み取ろうとすると失われる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 に答える