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)
Share:
15,425
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    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
    Admin over 7 years
    Okay, 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
    tdelaney over 7 years
    That won't help. "w" creates the file if it doesn't exist already.
  • Benjamin Engwall
    Benjamin Engwall over 7 years
    You'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
    tdelaney over 7 years
    It 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
    tdelaney over 7 years
    That doesn't help in this case. The file is being written, just not where OP thinks it should.
  • Saelyth
    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
    Admin over 7 years
    Okay. I tried that, and I received an error message, "sample.txt not found in directory"...
  • Benjamin Engwall
    Benjamin Engwall over 7 years
    Make sure you're using the right directory -- usually you can right click a file and view Properties for an explicit path to the file.