r/pythonhelp • u/ingervold • May 26 '22
Replace text in a file
Homework assignment. I have to open a file from a user input as read only. Close the file. Replace the text from the other user inputs. Open the file to write. Close it again. Then open and print.
file = input('Enter file name:')
old_word = input('Enter a string to be replaced: ')
new_word = input('Enter a string to be added: ')
with open(file, 'r') as infile:
file = infile.read()
infile.close()
with open(file, 'w') as infile:
file = infile.write()
file = file.replace(old_word, new_word)I keep getting an "OSError: [Errno 22]" when it tries to open 'file' again. Any help would be appreciated.
2
Upvotes
2
u/kaleidist May 26 '22
When you leave the
withcontext, then the file is automatically closed. I renamed the variables so hopefully that makes it easier to see what you were doing wrong.