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

发布于 2024-07-05 02:24:04 字数 143 浏览 10 评论 0原文

给定一个诸如“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 in Python? E.g. on Windows, I might end up with:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

拥醉 2024-07-12 02:24:05

总是获取当前脚本的正确文件名,即使是从另一个脚本中调用它也是如此。 当使用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.

赢得她心 2024-07-12 02:24:05

今天,您还可以使用基于 path.pyunipath 包: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 实用程序的干净接口

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.

烟─花易冷 2024-07-12 02:24:05

您可以使用它来获取特定文件的绝对路径。

from pathlib import Path

fpath = Path('myfile.txt').absolute()

print(fpath)

You can use this to get absolute path of a specific file.

from pathlib import Path

fpath = Path('myfile.txt').absolute()

print(fpath)
眼泪淡了忧伤 2024-07-12 02:24:05

给定一个路径,例如 mydir/myfile.txt,如何在 Python 中找到文件相对于当前工作目录的绝对路径?

我会这样做,

import os.path
os.path.join( os.getcwd(), 'mydir/myfile.txt' )

返回 '/home/ecarroll/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?

I would do it like this,

import os.path
os.path.join( os.getcwd(), 'mydir/myfile.txt' )

That returns '/home/ecarroll/mydir/myfile.txt'

暖阳 2024-07-12 02:24:05

如果您使用的是 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
贵在坚持 2024-07-12 02:24:05

如果有人使用 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
树深时见影 2024-07-12 02:24:05

安装第三方路径模块(位于PyPI),它将所有 os.path 函数和其他相关函数包装到对象上的方法中可以在任何使用字符串的地方使用:

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

Install a third-party path 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'
不甘平庸 2024-07-12 02:24:05
import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

请注意,如果文件(或目录)名称和位置的给定表达式可能包含前导 ~/(波形符指的是用户的主目录),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).

唱一曲作罢 2024-07-12 02:24:05

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
提赋 2024-07-12 02:24:05

您可以使用新的 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

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

夏天碎花小短裙 2024-07-12 02:24:04
>>> 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'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文