我正在另一台机器上读取文件。因此,我需要访问文件的完整路径。所以我尝试使用 pythons Pathlib 模块:a_path = '/dir1/subdir1/sample.txt'home = str(Path.home())a_path = str(home) + str(a_path)显然,上面的代码返回了我的完整路径。然而,当我阅读它时,我得到:FileNotFoundError: [Errno 2] No such file or directory: "/home/user'/dir1/subdir1/sample.txt'"如何修复上述错误?也许在串联中我遇到了问题。
3 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
试试这个。这使用os.path.join将两条路径连接在一起
import os
import pathlib
a_path = 'dir1/subdir1/sample.txt'
home = str(pathlib.Path.home())
print(os.path.join(home, a_path))
#/home/user/dir1/subdir1/sample.txt
皈依舞
TA贡献1851条经验 获得超3个赞
首先,'/dir1/subdir1/sample.txt'是绝对路径。如果您希望它是一个相对路径(似乎是这种情况),您应该使用'dir1/subdir1/sample.txt',所以没有前导/.
使用 pathlib 库,这将变得非常容易
>>> from pathlib import Path
>>> a_path = "dir1/subdir1/sample.txt"
>>> a_path = Path.home() / a_path
>>> print(a_path)
/home/pareto/dir1/subdir1/sample.txt
再次确保您没有使用绝对路径。否则你会得到以下
>>> print(Path.home() / "/dir1/subdir1/sample.txt")
/dir1/subdir1/sample.txt
添加回答
举报
0/150
提交
取消
