如何在Python中获取绝对文件路径
给定路径如"mydir/myfile.txt",如何在Python中找到相对于当前工作目录的绝对文件路径? 例如。 在Windows上,我最终会得到:
"C:/example/cwd/mydir/myfile.txt"
9个解决方案
756 votes
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
如果它已经是绝对路径也可以工作:
>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
sherbang answered 2019-01-19T13:14:00Z
54 votes
您可以使用新的Python 3.4库pathlib.(您也可以使用pip install pathlib获取Python 2.6或2.7。)作者写道:“这个库的目的是提供一个简单的类层次结构来处理文件系统路径和常见的 运营用户对他们采取行动。“
要在Windows中获取绝对路径:
>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'
或者在UNIX上:
>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'
文档在这里:[https://docs.python.org/3/library/pathlib.html]
twasbrillig answered 2019-01-19T13:15:03Z
53 votes
>>> import os
>>> os.path.abspath('mydir/myfile.txt')
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
Will Harris answered 2019-01-19T13:15:19Z
23 votes
更好的是,安装os.path模块,它将所有os.path函数和其他相关函数包装到一个对象的方法中,该对象可以在任何使用字符串的地方使用:
>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
Tom answered 2019-01-19T13:15:43Z
12 votes
今天你也可以使用基于path.py的unipath软件包:[http://sluggo.scrapping.cc/python/unipath/]
>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>
我建议使用这个包,因为它为常见的os.path实用程序提供了一个干净的接口。
Rudolf Olah answered 2019-01-19T13:16:23Z
2 votes
我更喜欢使用glob
以下是如何列出当前文件夹中的所有文件类型:
import glob
for x in glob.glob():
print(x)
这里是如何列出当前文件夹中的所有(例如).txt文件:
import glob
for x in glob.glob('*.txt'):
print(x)
以下是如何列出所选目录中的所有文件类型:
import glob
for x in glob.glob('C:/example/hi/hello/'):
print(x)
希望这能帮助你
F. Taylor answered 2019-01-19T13:17:20Z
0 votes
如果你在Mac上
import os
upload_folder = os.path.abspath("static/img/users")
这会给你一个完整的路径:
print(upload_folder)
将显示以下路径:
>>>/Users/myUsername/PycharmProjects/OBS/static/img/user
chikwapuro answered 2019-01-19T13:18:04Z
0 votes
如果有人使用python和linux并寻找文件的完整路径:
>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file
BND answered 2019-01-19T13:18:27Z
-1 votes
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"
filenameWithPath = os.path.join(filePathWithSlash, filename)
frank__aguirre answered 2019-01-19T13:18:42Z