首页 > 解决方案 > 如何在windows的python中打开路径

问题描述

我想在 Windows 10 中打开一个文件,但 open() 总是失败,即使尝试使用 PureWindowsPath、pathlib.Path 和 os.path.join

File "<input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 
'D:\\programmieren\\python\\pixie\\pixie\\data\\tokens\\databasecred.json'

我有一个包含字符串“./data/”的常量 DATAPATH,之后我添加了“tokens/databasecred.json”来创建一个文件变量。

我只想用函数 open() 打开它,但由于转义而失败,似乎是由所述函数添加的。我尽一切努力让它在 Windows 中工作。

from pixie import data
file = data.DATAPATH + 'tokens/databasecred.json'

"""Examples won't work because I always get the error with wrong path said above"""

file = os.path.relpath(file)
f = open(file, 'r', encoding='utf-8')

f = open(os.path.relpath(os.path.join(os.path.dirname(file), os.path.basename(file))))

f = open(os.path.abspath(os.path.join(os.path.dirname(file), os.path.basename(file))))

file = Path(file) 
f = open(file, 'r', encoding='utf-8')

file = PureWindowsPath(file)
f = open(file, 'r', encoding='utf-8')

这是控制台的输出

    print(data.DATAPATH)
    >>>./data/

    file = data.DATAPATH + 'tokens/databasecred.json'
    file = os.path.relpath(file)

    f = open(file, 'r', encoding='utf-8')
    >>>Traceback (most recent call last):
      File "<input>", line 1, in <module>
    FileNotFoundError: [Errno 2] No such file or directory:                     
    'data\\tokens\\databasecred.json'

    f = open(os.path.relpath(os.path.join(os.path.dirname(file),     
    os.path.basename(file))))
    >>>Traceback (most recent call last):
      File "<input>", line 1, in <module>
    FileNotFoundError: [Errno 2] No such file or directory:         
    'data\\tokens\\databasecred.json'

    f = open(os.path.abspath(os.path.join(os.path.dirname(file),         
    os.path.basename(file))))
    >>>Traceback (most recent call last):
      File "<input>", line 1, in <module>
    FileNotFoundError: [Errno 2] No such file or directory:     
    'D:\\programmieren\\python\\pixie\\pixie\\data\\tokens\\databasecred.json'

    file = Path(file) 

    f = open(file, 'r', encoding='utf-8')
    >>>Traceback (most recent call last):
      File "<input>", line 2, in <module>
    FileNotFoundError: [Errno 2] No such file or directory: 'data\\tokens\\databasecred.json'

    file = PureWindowsPath(file)
    f = open(file, 'r', encoding='utf-8')
    >>>Traceback (most recent call last):
      File "<input>", line 2, in <module>
    FileNotFoundError: [Errno 2] No such file or directory: 'data\\tokens\\databasecred.json'

标签: python-3.xwindows

解决方案


推荐阅读