python-3.x - 如何在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'
解决方案
推荐阅读
- php - 文件上传后图像(src)不刷新->图像
- python - 进程、内存和网络资源跟踪器
- python - Numpy,矩阵乘法
- javascript - 如何使用过滤器或某些函数按键和值过滤对象数组
- python - pip + 如何下载最新版本的 .whl 文件
- node.js - 使用具有正确标头和 SHA512 散列令牌的节点生成正确 TOTP 时出错?
- c# - .NET 两个以类开头的同名包
- react-native - 登录后如何将异步存储中的令牌分配给 app.js 中的标头。在本机反应
- ruby-on-rails - Angular httpClient 发布请求发送重复的相同参数和空白值,为什么?
- mongodb - 猫鼬事务期间创建集合的正确方法