标签归档:absolute-path

如何在Python中获取绝对文件路径

问题:如何在Python中获取绝对文件路径

给定路径,例如"mydir/myfile.txt",我如何找到相对于Python中当前工作目录的文件的绝对路径?例如在Windows上,我可能最终得到:

"C:/example/cwd/mydir/myfile.txt"

Given a path such as "mydir/myfile.txt", how do I find the file’s absolute path relative to the current working directory in Python? E.g. on Windows, I might end up with:

"C:/example/cwd/mydir/myfile.txt"

回答 0

>>> 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'
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

回答 1

您可以使用新的Python 3.4库pathlib。(您也可以使用来为Python 2.6或2.7获取它pip install pathlib。)作者写道:“该库的目的是提供一个简单的类层次结构来处理文件系统路径以及用户对其进行的常见操作。”

在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

You could use the new Python 3.4 library pathlib. (You can also get it for Python 2.6 or 2.7 using pip install pathlib.) The authors wrote: “The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them.”

To get an absolute path in Windows:

>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'

Or on UNIX:

>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'

Docs are here: https://docs.python.org/3/library/pathlib.html


回答 2

更好的是,安装模块(位于上PyPI),它将所有os.path功能和其他相关功能包装到对象上的方法中,无论使用什么字符串,都可以使用该方法:

>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>

Better still, install the module (found on PyPI), it wraps all the os.path functions and other related functions into methods on an object that can be used wherever strings are used:

>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>

回答 3

今天,您还可以使用unipath基于以下内容的软件包path.pyhttp : //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实用程序提供了一个干净的接口

Today you can also use the unipath package which was based on path.py: 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
>>>

I would recommend using this package as it offers a clean interface to common os.path utilities.


回答 4

Python 3.4+的更新pathlib实际上回答了这个问题:

from pathlib import Path

relative = Path("mydir/myfile.txt")
absolute = relative.absolute()  # absolute is a Path object

如果只需要一个临时字符串,请记住,您可以将Path对象与中的所有相关功能一起使用os.path,当然包括abspath

from os.path import abspath

absolute = abspath(relative)  # absolute is a str object

Update for Python 3.4+ pathlib that actually answers the question:

from pathlib import Path

relative = Path("mydir/myfile.txt")
absolute = relative.absolute()  # absolute is a Path object

If you only need a temporary string, keep in mind that you can use Path objects with all the relevant functions in os.path, including of course abspath:

from os.path import abspath

absolute = abspath(relative)  # absolute is a str object

回答 5

import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

请注意expanduser(在Unix上),如果给定的文件(或目录)名称和位置表达式可能包含前导~/(代字号指向用户的主目录),并且expandvars可以处理任何其他环境变量(如$HOME),则这是必需的。

import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

Note that expanduser is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/(the tilde refers to the user’s home directory), and expandvars takes care of any other environment variables (like $HOME).


回答 6

始终获取当前脚本的文件名权,即使它是从另一个脚本中调用。使用时特别有用subprocess

import sys,os

filename = sys.argv[0]

从那里,您可以使用以下命令获取脚本的完整路径:

>>> os.path.abspath(filename)
'/foo/bar/script.py'

通过/..在目录的层次结构中添加您想要向上跳转的次数,它还使导航文件夹更加容易。

要获取cwd:

>>> os.path.abspath(filename+"/..")
'/foo/bar'

对于父路径:

>>> os.path.abspath(filename+"/../..")
'/foo'

通过"/.."与其他文件名结合使用,您可以访问系统中的任何文件。

This always gets the right filename of the current script, even when it is called from within another script. It is especially useful when using subprocess.

import sys,os

filename = sys.argv[0]

from there, you can get the script’s full path with:

>>> os.path.abspath(filename)
'/foo/bar/script.py'

It also makes easier to navigate folders by just appending /.. as many times as you want to go ‘up’ in the directories’ hierarchy.

To get the cwd:

>>> os.path.abspath(filename+"/..")
'/foo/bar'

For the parent path:

>>> os.path.abspath(filename+"/../..")
'/foo'

By combining "/.." with other filenames, you can access any file in the system.


回答 7

模块os提供了一种找到Abs路径的方法。

但是,Linux中的大多数路径都以~(波浪号)开头,因此效果不理想。

因此您可以使用srblib它。

>>> import os
>>> os.path.abspath('~/hello/world')
'/home/srb/Desktop/~/hello/world'
>>> from srblib import abs_path
>>> abs_path('~/hello/world')
'/home/srb/hello/world'

使用安装 python3 -m pip install srblib

https://pypi.org/project/srblib/

Module os provides a way to find abs path.

BUT most of the paths in Linux start with ~ (tilde), which doesn’t give a satisfactory result.

so you can use srblib for that.

>>> import os
>>> os.path.abspath('~/hello/world')
'/home/srb/Desktop/~/hello/world'
>>> from srblib import abs_path
>>> abs_path('~/hello/world')
'/home/srb/hello/world'

install it using python3 -m pip install srblib

https://pypi.org/project/srblib/


回答 8

我更喜欢使用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)

希望这对你有帮助

I prefer to use glob

here is how to list all file types in your current folder:

import glob
for x in glob.glob():
    print(x)

here is how to list all (for example) .txt files in your current folder:

import glob
for x in glob.glob('*.txt'):
    print(x)

here is how to list all file types in a chose directory:

import glob
for x in glob.glob('C:/example/hi/hello/'):
    print(x)

hope this helped you


回答 9

如果您使用的是Mac

import os
upload_folder = os.path.abspath("static/img/users")

这将为您提供完整的路径:

print(upload_folder)

将显示以下路径:

>>>/Users/myUsername/PycharmProjects/OBS/static/img/user

if you are on a mac

import os
upload_folder = os.path.abspath("static/img/users")

this will give you a full path:

print(upload_folder)

will show the following path:

>>>/Users/myUsername/PycharmProjects/OBS/static/img/user

回答 10

如果有人使用python和linux并寻找文件的完整路径:

>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file

In case someone is using python and linux and looking for full path to file:

>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file