In Python, writing to a text file is not creating a file in the directory I expected

Question:

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. Why doesn’t it even seem to create the file?

Here’s the code:

text = 'Sample text.'
saveFile = open('file.txt','w')
saveFile.write(text)
saveFile.close()

I run it from Python IDLE. I’m trying to save the file to my Desktop.

Asked By: Ray Technologies

||

Answers:

Make sure to call the .close() function rather than simply referencing the method on your last line. Note that the file will be created in the same directory that your .py module is located, so make sure you’re looking in the right place for your output.

Answered By: Benjamin Engwall

are you sure authority to write file

code better like below

#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''

text = 'Sample text.'

with open('sample.txt', 'w') as f:
    f.write(text)
Answered By: 黄哥Python培训

Does the file exists? Use this code to create it.

open('sample.txt', 'a').close()

To have that line on the code won’t hurt if the file is already created because it opens the file and closes without adding anything. However if it doesn’t exists it creates it with the specific encoding that python uses (I think) so you don’t have to worry about that. After that, your code should work:

text = 'Sample text.'
saveFile = open('file.txt','w')
saveFile.write(text)
saveFile.close()
Answered By: Saelyth

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)
Answered By: tdelaney
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.