windows中的python exe未写入

2024-06-30 12:22:11 发布

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

我已使用pyinstaller将python程序转换为exe。My exe创建一个临时文件夹_MEIxxxxx以保存文件。在同一个文件夹中,有一个文件正在被程序更改,但不幸的是,它没有发生。 在程序中,我将文件夹更改为上面的文件夹:

os.chdir('C:\\Users\\Public')
for foldername in os.listdir():
if foldername.startswith('_MEI'):
    myfolder = foldername
    os.chdir('C:\\Users\\Public'+myfolder+'\\Quiz')

提前谢谢


Tags: 文件in程序文件夹forosmypublic
1条回答
网友
1楼 · 发布于 2024-06-30 12:22:11

这不起作用:

os.chdir('C:\\Users\\Public'+myfolder+'\\Quiz')

因为myfolder在开始时不包含\

不要硬编码C:\Users\Public,使用PUBLICenv。变量

避免chdir,它相当于所有模块之间共享的全局变量。如果某个模块需要一个当前目录,另一个则需要另一个

您的尝试看起来更像是移植到python的shell脚本cd xxx; ls; ...。改掉这个习惯

改用绝对路径/作为参数传递的路径。我的建议:

pubdir = os.getenv("PUBLIC")
for foldername in os.listdir(pubdir):
  if foldername.startswith('_MEI'):
      myfolder = foldername
      quizdir = os.path.join(pubdir,myfolder,'Quiz')
      # now do something with quizdir

如果您需要一个绝对目录来运行系统调用,subprocess函数有一个cwd参数。所以你可以避免99%的时间

相关问题 更多 >