Python Forum

Full Version: file handling Newbee question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am a pascal programmer learning python
Raspberry pi 2, python 3.9
f = open("temps.txt")
f.write("attemt1\r\n")
f.close
Nothing is written to the file. When I add the next lines to the script
f = open("temps.txt","r")
Now there is a new line in the file
What do I do wrong?
Thanks for your attention. Teunis
I suggest to read Reading and Writing files on python.org

You didn't specified mode while opening the file and it defaults to 'r' (read). But you want to write, so you need provide 'w' or similar ('a', 'r+', etc).

And keep in mind:

Quote:Warning Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

So you probably better off changing your habits and open files with open('tempts.txt', 'w') as f:
Thanks for the advice!
The mode was "a+" I forgot to write it
the hint to use
with openfile() as f: 
it solved my problem
Thanks