我通过 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')
希望这对某人有所帮助。
我是一名优秀的程序员,十分优秀!