1
How do I have files become written within a loop?
TheFlooBearer (2)

https://repl.it/@TheFlooBearer/The-way-you-will-die

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?

You are viewing a single comment. View All
1
JustARatherRidi (185)

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.

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 jsonstore.io 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 = 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!

2
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.

1
JustARatherRidi (185)

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

1
TheFlooBearer (2)

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