In Python, writing to a text file not working
15,425
You are writing the file to the current working directory, but that directory isn't the one you want. You can write files relative to your home or desktop directory by generating absolute paths to those directories.
import os
home_dir = os.path.expanduser('~')
desktop_dir = os.path.join(home_dir, 'Desktop')
Now you can use it for your files. Note I am using a context manager so I don't have to explicitly close the file:
text = 'Sample text.'
with open(os.path.join(desktop_dir, 'file.txt'),'w') as savefile:
saveFile.write(text)
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 15, 2022Comments
-
Admin about 2 years
So I've been working on a project with python 3, and I need to store some data on a .txt file. When I run the code, there is no error message, it doesn't even create the file. Please help.
Here's the code:
text = 'Sample text.' saveFile = open('file.txt','w') saveFile.write(text) saveFile.close()
-
Admin over 7 yearsOkay, so I found the file that was created, but when I move it to somewhere, like the desktop, and try to write it again, nothing happens.
-
tdelaney over 7 yearsThat won't help. "w" creates the file if it doesn't exist already.
-
Benjamin Engwall over 7 yearsYou'll have to reference the specific file path to your .txt file if it's no longer in the same directory as the Python module.
C:\Users\User\Desktop\sample.txt
or something like that. -
tdelaney over 7 yearsIt doesn't do any good... Files aren't created with a persistent encoding. Any code that reads or writes it needs to know what the encoding is.
-
tdelaney over 7 yearsThat doesn't help in this case. The file is being written, just not where OP thinks it should.
-
Saelyth over 7 years"w" should create it indeed, but not always does. I found some months ago that creating files with "a" removes some of the bugs I was having on my code and I've been using it ever since.
-
Admin over 7 yearsOkay. I tried that, and I received an error message, "sample.txt not found in directory"...
-
Benjamin Engwall over 7 yearsMake sure you're using the right directory -- usually you can right click a file and view Properties for an explicit path to the file.