user9245872
user9245872

Reputation:

Python writing data to file only works when run from console

If I run

file = open("BAL.txt","w")
I = '200'
file.write(I)
file.close

from a script, it outputs nothing in the file. (It literally overwrites the file with nothing)

Furthermore, running cat BAL.txt just goes to the next line like nothing is in the file.

But if I run it line by line in a python console it works perfectly fine. Why does this happen. ( I am a begginner learning python the mistake may be super obvious. I have thrown about 2 hours into trying to figure this out)
Thanks in advance

Upvotes: 2

Views: 195

Answers (3)

Xantium
Xantium

Reputation: 11605

You aren't closing your file properly. To close it you are missing the () at the end of file.close so it should look like this:

file = open("BAL.txt", "w")
file.write("This has been written to a file")
file.close()

This site has the same example and may be of some use to you.


Another way, especially useful when you are appending multiple values into a single file is to use something like with open("BAL.txt","w") as file:. Here is your script rewritten to include this example:

I = '200'
with open("BAL.txt","w") as file:
    file.write(I)

This opens our file with the value file and allows us to write values to it. Also note that file.close() is not needed here and when appending text w+ needs to be used.

Upvotes: 4

Hippolippo
Hippolippo

Reputation: 813

to write to a file you do this:

file = open("file.txt","w")
file.write("something")
file.close()

when you use file.write() it deletes all of the contents of the file, if you want to write to the end of the file do this:

file = open("file.text","w+")
file.write(file.read()+"something")
file.close()

There are other ways to do this but this one is the most intuitive (not the most efficient), also the other way tends to be buggy so there is no reason to post it because this is reliable.

Upvotes: 3

Jaden Costa
Jaden Costa

Reputation: 78

Firstly, you're missing the parentheses when you're closing the file. Secondly, writing to a file should be done like this:

file = open("BAL.txt", "w")
file.write("This has been written to a file")
file.close()

Let me know if you have any questions.

Upvotes: 2

Related Questions