2

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.

John Jay
  • 83
  • 3
  • 9

3 Answers3

3

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

Use 'r'to read. See the link

f p
  • 3,165
  • 1
  • 27
  • 35
2

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)
Chayim
  • 36
  • 1
  • shutil does not actually copy files. There's [a big fat warning right at the top of the docs](https://docs.python.org/3/library/shutil.html). "this means that file owner and group are lost as well as ACLs. On Mac OS, the resource fork and other metadata are not used. This means that resources will be lost and file type and creator codes will not be correct. On Windows, file owners, ACLs and alternate data streams are not copied." – gman Nov 25 '19 at 03:07
0

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.

jurgenreza
  • 5,856
  • 2
  • 25
  • 37