In my code, I hope to have the program execution notice that the variables at the beginning are mentioned, and then once it gets to the end, to write those variables into the 'names.txt' file. Originally, I had hoped that the program would add the output into the file, but it does not seem to be adding anything at all. Where am I making the mistake?
There are two things wrong with your program.
First off, repl.it's file writing is a bit wonky. So you'll have to stick to running your code locally if you're trying to do file writing.
Secondly, you can't open a file in read mode and in write mode at the same time. This means that you'd have to do
fw = open('names.txt', 'w').
You can see how closing files and opening new ones can get confusing. This is why you should use the
with statement. Here's how it works.
Instead of this
f = open('file.txt', 'r') data = f.read() f.close()
You'd write this
with open('file.txt', 'r') as f: data = f.read()
This way you don't have to worry about what files are open or what you need to close.
Here's a repl with that cleaned up
Note, however, that this won't work on repl.it because file writing doesn't work very well here at repl.it. But this code does work locally.
Let me know if i lost you anywhere!