Writing to .txt file in python


#1

Hi all!

I’m trying to write data to .txt files using a python script. The script runs as expected in IDLE but when i run it in atom(using the ‘script’ package), nothing is written to the file and nor is a new file created. Why does this happen and how can this be fixed ? Are there any other packages beside ‘script’ which can be used to run python code from within atom?


#2

Please share with us the code you are running (a screenshot would be best). You’re saying that the package script runs the code and reports a successful execution, but no file is created?


#3

This is the code I am using. Pretty basic and straight forward. Note how the output window at the bottom shows successful execution even though the file hasn’t been created and/or written to. Tested this in IDLE, work perfectly.


#4

The file you write (abxde.txt) is probably located inside .atom directory because you do not specify it’s absolute path.
i suggest using os module (os.path or os.cwd)

or change current working directory settings in Atom (Settings --> Packages —> Script)


#5

You haven’t demonstrated that the file doesn’t exist, and I believe that @serafeimgr is right about what the script thinks that you mean to do. However, I believe that the file has been created in the folder C:\Users\Achintya Mohan\AppData\Local\atom\app-1.27.1, since that’s the place where Atom starts.


#6

Thanks for the help! Could you give an example using the os module to write the file to a particular location?


#7

Sure, here is an exaple for writing in your current directory.
Keep in mind that i use os for getting the current working directory and i also use path.join in order to keep the code operating system agnostic.

import os

def main():
    """
    :return:
    """
    with open(os.path.join(os.getcwd(), 'myfile.txt'), 'w') as text_file:
        text_file.write('Hello World!')


if __name__ == '__main__':
    main()