运行python的.py文件时无法用python编写文件。但当我在pycharm中运行它时,它实际上起作用了

2024-09-24 22:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我还是python新手,我很难理解为什么我的py文件在运行它的.py文件时不写文本。但每当我在pycharm上运行它时,它总是有效的。我在文件上写东西时也尝试了很多方法,但除非我在Pycharm上运行它,否则它仍然不会在文件中写任何东西。我错过什么了吗?请帮忙

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

Tags: 文件pathpytxtcloseoutputmyas
2条回答

确保:

  1. 您正在运行python main.py
  2. 您没有同时安装python2和python3,这可能导致PATH变量中的“python.exe”实际上是python2。如果是,请编辑路径变量

这几乎肯定是工作目录的问题。脚本的位置并不意味着将在那里创建文件,并且您可能在错误的位置查找结果文件。在脚本中添加一行:

import os
print(os.getcwd())

然后检查wifipasswords.txt是否在该目录中(应该是)。如果要将文件显式放置在与脚本相同的目录中(一般来说,这不是一个好主意,因为脚本通常安装在受保护的位置,但适合个人使用),可以使用以下方法显式更改工作目录:

import os
import os.path

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

或者在不更改工作目录的情况下明确限定文件名,例如:

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

相关问题 更多 >