Chirag
Chirag

Reputation: 1239

Copy contents of one file into other using Python 3

I have written following piece of code with an intention to copy contents of abc.txt into another file xyz.txt

but the statement b_file.write(a_file.read()) doesn't seem to work as intended. If I replace a_file.read() with some string, it (the string) gets printed.

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

How do I go about this?

Upvotes: 1

Views: 8379

Answers (3)

jfs
jfs

Reputation: 414915

To copy the contents of abc.txt to xyz.txt, you could use shutil.copyfile():

import shutil

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

Upvotes: 2

martineau
martineau

Reputation: 123531

You're calling a_file.read() twice. The first time it reads the whole file, but that is lost with the attempt to do it again after opening xyz.txt -- so nothing gets written to that file. Try this to avoid the problem:

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

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

You're looking for shutil.copyfileobj().

Upvotes: 10

Related Questions