Q:

blank file while copying a file in python

I have a function takes a file as input and prints certain statistics and also copies the file into a file name provided by the user.  Here is my current code:
def copy_file(option):
infile_name = input("Please enter the name of the file to copy: ")
infile = open(infile_name, 'r')
outfile_name = input("Please enter the name of the new copy:  ")
outfile = open(outfile_name, 'w')
slist = infile.readlines()
if option == 'statistics':
    for line in infile:
        outfile.write(line)
    infile.close()
    outfile.close()
    result = []
    blank_count = slist.count('\n')
    for item in slist:
        result.append(len(item))
    print('\n{0:<5d} lines in the list\n{1:>5d} empty lines\n{2:>7.1f} average character per line\n{3:>7.1f} average character per non-empty line'.format(
        len(slist), blank_count, sum(result)/len(slist), (sum(result)-blank_count)/(len(slist)-blank_count)))

copy_file('statistics')

It prints the statistics of the file correctly, however the copy it makes of the file is empty. If I remove the readline() part and the statistics part, the function seems to make a copy of the file correctly. How can I correct my code so that it does both. It's a minor problem but I can't seem to get it.

A:

The reason the file is blank is that
slist = infile.readlines()

is reading the entire contents of the file, so when it gets to
 for line in infile:

there is nothing left to read and it just closes the newly truncated (mode w) file leaving you with a blank file.
I think the answer here is to change your for line in infile: to for line in slist:
def copy_file(option):
    infile_name= input("Please enter the name of the file to copy: ")
    infile = open(infile_name, 'r')
    outfile_name = input("Please enter the name of the new copy:  ")
    outfile = open(outfile_name, 'w')
    slist = infile.readlines()
    if option == 'statistics':
        for line in slist:
            outfile.write(line)
        infile.close()
        outfile.close()
        result = []
        blank_count = slist.count('\n')
        for item in slist:
            result.append(len(item))
        print('\n{0:<5d} lines in the list\n{1:>5d} empty lines\n{2:>7.1f} average character per line\n{3:>7.1f} average character per non-empty line'.format(
            len(slist), blank_count, sum(result)/len(slist), (sum(result)-blank_count)/(len(slist)-blank_count)))

copy_file('statistics')

Having said all that, consider if it's worth using your own copy routine rather than shutil.copy - Always better to delegate the task to your OS as it will be quicker and probably safer (thanks to NightShadeQueen for the reminder)!

