如何解决如何在Python中获取绝对文件路径? 去掉反斜杠
给定一个路径,例如“mydir/myfile.txt”,我如何在 Python 中找到相对于当前工作目录的文件的绝对路径?例如。在 Windows 上,我可能会得到:
"C:/example/cwd/mydir/myfile.txt"
。
我试过:mypath = os.path.abspath("../mydir/myfile.txt")
。但我得到了:
>> print(mypath)
C:\example\cwd\mydir\myfile.txt
请注意,当我执行 mypath
时,我有 C:\\example\\cwd\\mydir\\myfile.txt
。
解决方法
除了 C:\example\cwd\mydir\myfile.txt
之外,您希望什么?
您看到的是绝对的 Windows 文件路径。
Windows 使用反斜杠作为其文件路径,而 Linux 使用正斜杠。
python os.path
包自动处理转换,因此尽管您输入了 Linux 样式的路径(至少几乎是因为 Linux 不知道像 C: 这样的驱动器),它会自动转换为 Windows(当您运行代码时在 Windows 机器上)。
另见:What is the filepath difference between window and linux in python3?
,根据您对我的评论的回答,您想要的是使用文件的相对路径,而不是文件的绝对路径。
我建议您使用 os.path.relpath
来计算从当前工作目录到文件的相对路径:
import os.path
# inputs
absolute_path_to_file = r"C:\example\cwd\mydir\myfile.txt"
current_working_directory = os.path.abspath(os.path.curdir) # C:\example\cwd\my_other_dir
# using os.path.relpath
relative_path_from_current_working_directory_to_file = \
os.path.relpath(absolute_path_to_file,current_working_directory)
# result
print(relative_path_from_current_working_directory_to_file) # ..\mydir\myfile.txt
如果需要,您可以省略 os.path.relpath
(名为 start
)的第二个参数,因为它默认为您的当前目录(请参阅 os.curdir
),这样您就可以简单地执行以下操作:
relative_path_from_current_working_directory_to_file = \
os.path.relpath(absolute_path_to_file)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。