Ray Technologies
Ray Technologies

Reputation: 33

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

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.

Upvotes: 3

Views: 20928

Answers (4)

tdelaney
tdelaney

Reputation: 77337

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)

Upvotes: 4

Saelyth
Saelyth

Reputation: 1734

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()

Upvotes: -1

黄哥Python培训
黄哥Python培训

Reputation: 249

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)

Upvotes: -1

Benjamin Engwall
Benjamin Engwall

Reputation: 294

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.

Upvotes: 0

Related Questions