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@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
//
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor