简体   繁体   中英

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

Make sure that:

  1. you are running python main .py
  2. that you don't have python2 and python3 installed together, resulting that maybe "python.exe" in PATH variable is actually python2. If you do, edit path variable.

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, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM