[Tutor] Writing to a file/changing the file name

Michael Lewis mjolewis at gmail.com
Thu Feb 23 06:04:41 CET 2012


Hi everyone,

I have a program where I open a file (recipe.txt), I read that file and
write it to another file. I am doing some multiplying of numbers in
between; however, my question is, when I name the file I am writing to, the
file extension is changed, but the file name is not. What am I doing wrong?

Code:

import Homework5_1 as multiply

def MultiplyNumbersInFile(file_name, multiplier):
    '''Open file/read file/write new file that doubles all int's in the
    read file'''
    try:
        read_file = open(file_name)
    except IOError:
        print "I can't find file: ", file_name
        return
    new_file_name = file_name + '2'
    try:
        write_file = open(new_file_name, 'w')
    except IOError:
        read_file.close()
        print "I can't open file: ", new_file_name
        return
    for line in read_file:
        new_line = line.split()
        new_line = ''.join(multiply.MultiplyText(new_line, multiplier))
        write_file.write(new_line + '\n')
    read_file.close()
    write_file.close()

def main():
    file_name = raw_input('What file do you want to open? ')
    multiplier = multiply.GetUserNumber()
    MultiplyNumbersInFile(file_name, multiplier)

if __name__ == '__main__':
    main()

What I am doing in IDLE:

What file do you want to open? recipe.txt
Enter a multiplier: 2

The file that is actually created in my directory is still named recipe;
however, the file type is now TXT2 File. How do I make it so I am updating
the file name to recipe2 instead of the file type?


-- 
Michael J. Lewis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120222/8a6aa6f5/attachment-0001.html>


More information about the Tutor mailing list