John Jay
John Jay

Reputation: 83

How to copy a file in Python?

I need to copy a file specified by the user and make a copy of it (giving it a name specified by the user). This is my code:

import copy

def main():

    userfile = raw_input('Please enter the name of the input file.')
    userfile2 = raw_input('Please enter the name of the output file.')

    infile = open(userfile,'r')

    file_contents = infile.read()

    infile.close()

    print(file_contents)


    userfile2 = copy.copy(file_contents)

    outfile = open(userfile2,'w+')

    file_contents2 = outfile.read()

    print(file_contents2)

main()

Something strange is happening here, as it doesn't print the contents of the second file, outfile.

Upvotes: 2

Views: 3380

Answers (3)

Chayim
Chayim

Reputation: 46

Python's shutil is a much more portable method of copying files. Try the sample below:

import os
import sys
import shutil

source = raw_input("Enter source file path: ")
dest = raw_input("Enter destination path: ")

if not os.path.isfile(source):
    print "Source file %s does not exist." % source
    sys.exit(3)

try:
    shutil.copy(source, dest)
except IOError, e:
    print "Could not copy file %s to destination %s" % (source, dest)
    print e
    sys.exit(3)

Upvotes: 3

jurgenreza
jurgenreza

Reputation: 6086

Why don't you just write the input file contents to the output file?

userfile1 = raw_input('input file:')
userfile2 = raw_input('output file:')

infile = open(userfile1,'r')
file_contents = infile.read()    
infile.close()

outfile = open(userfile2,'w')
outfile.write(file_contents)
outfile.close()

What copy does is that it shallow copies the objects in python, has nothing to do with copying files.

What this line actually does is that it copies input file contents over the name of the output file:

userfile2 = copy.copy(file_contents)

You lose your output file name and no copy operation happens.

Upvotes: 0

f p
f p

Reputation: 3223

If you are reading outfile, why do you open it with 'w+'? This truncates the file.

Use 'r'to read. See the link

Upvotes: 3

Related Questions