Search code examples
pythonfilepycharm

Can't write files in python when I run it's .py file. But when I run it in pycharm, it actually work


I'am still new in python and im having a hard time why does my py file wont write text when i run it its .py file. But whenever i run it on pycharm it always works. I also tried many option when writing on a file and it still won't write anything in file unless i run it on Pycharm. Am i missing something? pleasee need help

here the .py file im telling whenever i run this, nothing happens

path = 'wifipasswords.txt'
my_open = open(path, 'w+')
my_open.write(final_output)
print(final_output)
my_open.close()


//MY attempts
# with open("wifipasswords.txt", "w") as f:
#     print(final_output, file=f)

# pathlib.Path("wifipasswords.txt").write_text(final_output)
# with open("wifipasswords.txt", "w") as f:
#     f.write(final_output)

# file = open("wifipasswords.txt", "w")
# file.write(final_output)
# file.close()

Solution

  • This is almost certainly an issue of your working directory. The location of the script does not imply that that is where the file will be created, and you're probably looking in the wrong place for the resulting file. Add a line to your script:

    import os
    print(os.getcwd())
    

    then check if wifipasswords.txt is in that directory (it should be). If you want to explicitly place the file in the same directory as the script (not a good idea in general since scripts are often installed in protected locations, but okay for personal use), you can explicitly change the working directory with something like:

    import os
    import os.path
    
    os.chdir(os.path.dirname(__file__))
    

    or explicitly qualify the file name without changing your working directory, e.g.:

    path = os.path.join(os.path.dirname(__file__), 'wifipasswords.txt')