gpt4 book ai didi

python - 如何用python在windows中打开文件?

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:21 25 4
gpt4 key购买 nike

我通过 sys.argv 传递文件名,其中使用斜杠而不是反斜杠。我正在使用 os.path.normpath 和 os.path.join 但在尝试打开文件时出现异常 no such file or directory: 并且路径带有双反斜杠。我花了几个小时寻找解决方案,但没有任何效果。

我尝试了在谷歌上找到的所有教程,但我总是遇到同样的问题。我只是不断收到双反斜杠。我也尝试过像示例中那样对路径进行硬编码。

filepath = os.path.normpath(os.path.join('D:/dir1/dir2/dir3', 'myfile.txt'))
try:
my_file = open(filepath, 'w+')
except Exception as e:
print('Cannot create/open file w+!\n{}'.format(e))

我需要能够打开该文件。

最佳答案

在 python 脚本中它可以使用:

file_path =  os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini')

但是如果我需要使用 py2exe 构建程序,则 __file__ 不起作用,我使用:

file_path =  os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'config.ini')

希望这对某人有所帮助。

关于python - 如何用python在windows中打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56575529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com