Ask coding questions

← Back to all posts
How do I have files become written within a loop?
TheFlooBearer (2)

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?

Answered by JustARatherRidi (191) [earned 5 cycles]
View Answer
JustARatherRidi (191)

There are two things wrong with your program.

First off,'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.

If you're looking for a way to store the data online, you'd have to use a database. And pretty much the easiest way to do that would be by using and leon's client

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 fr.close() before 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 =

You'd write this

with open('file.txt', 'r') as f:
    data =

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 because file writing doesn't work very well here at But this code does work locally.

Let me know if i lost you anywhere!

TheFlooBearer (2)

@JustARatherRidi Okay! Thanks. I get what you are saying. I'll find a tutorial somewhere on how to upload files somewhere. Thanks again, this helps a lot.

JustARatherRidi (191)

@TheFlooBearer Anytime! What exactly do you have in mind when you say uploading files online? What do you plan to do with these files?

TheFlooBearer (2)

@JustARatherRidi It's mainly just as an exercise. Nothing too special.