[Tutor] Writing to a file/changing the file name
Christian Witts
cwitts at compuscan.co.za
Thu Feb 23 06:26:23 CET 2012
On 2012/02/23 07:04 AM, Michael Lewis wrote:
> 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
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
That's because your `file_name` variable contains the file name and
extension. You will need to split it into it's component pieces and
then put it back together once you've changed the name, and for that you
can use os.path.splitext
>>> import os
>>> filename, extension = os.path.splitext('recipe.txt')
>>> print (filename, extension)
('recipe', '.txt')
>>> new_filename = filename + '2' + extension
>>> print new_filename
'recipe2.txt'
--
Christian Witts
Python Developer
//
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120223/1a118436/attachment.html>
More information about the Tutor
mailing list