python 文件对象的绝对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2458676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:41:50  来源:igfitidea点击:

Absolute path of a file object

pythonfilefilesystems

提问by astrofrog

This has been discussed on StackOverflow before - I am trying to find a good way to find the absolute path of a file object, but I need it to be robust to os.chdir(), so cannot use

这已经在 StackOverflow 上讨论过 - 我试图找到一种找到文件对象绝对路径的好方法,但我需要它对 健壮os.chdir(),所以不能使用

f = file('test')
os.path.abspath(f.name)

Instead, I was wondering whether the following is a good solution - basically extending the file class so that on opening, the absolute path of the file is saved:

相反,我想知道以下是否是一个好的解决方案 - 基本上是扩展文件类,以便在打开时保存文件的绝对路径:

class File(file):

    def __init__(self, filename, *args, **kwargs):
        self.abspath = os.path.abspath(filename)
        file.__init__(self, filename, *args, **kwargs)

Then one can do

然后一个可以做

f = File('test','rb')
os.chdir('some_directory')
f.abspath # absolute path can be accessed like this

Are there any risks with doing this?

这样做有什么风险吗?

采纳答案by bignose

One significant risk is that, once the file is open, the process is dealing with that file by its file descriptor, notits path. On many operating systems, the file's path can be changed by some other process(by a mvoperation in an unrelated process, say) and the file descriptor is still valid and refers to the same file.

一个重大风险是,一旦文件打开,进程将通过其文件描述符而不是其路径来处理该文件。在许多操作系统上,文件的路径可以被其他一些进程更改(例如通过mv在不相关进程中的操作),并且文件描述符仍然有效并引用同一个文件。

I often take advantage of this by, for example, beginning a download of a large file, then realising the destination file isn't where I want it to be, and hopping to a separate shell and moving it to the right location – while the download continues uninterrupted.

我经常利用这一点,例如,开始下载一个大文件,然后意识到目标文件不在我想要的位置,然后跳到一个单独的 shell 并将其移动到正确的位置——而下载继续不间断。

So it is a bad idea to depend on the path remaining the samefor the life of the process, when there's no such guarantee given by the operating system.

因此,当操作系统没有提供这样的保证时,依赖路径在进程的生命周期中保持不变是一个坏主意

回答by Glenn Maynard

It depends on what you need it for.

这取决于你需要它做什么。

As long as you understand the limitations--someone might move, rename, or hard-link the file in the interim--there are plenty of appropriate uses for this. You may want to delete the file when you're done with it or if something goes wrong while writing it (eg. gcc does this when writing files):

只要您了解这些限制——在此期间,有人可能会移动、重命名或硬链接文件——就有很多合适的用途。您可能希望在完成文件后或在编写文件时出现问题时将其删除(例如,gcc 在编写文件时会这样做):

f = File(path, "w+")
try:
    ...
except:
    try:
        os.unlink(f.abspath)
    except OSError: # nothing we can do if this fails
        pass
    raise

If you just want to be able to identify the file in user messages, there's already file.name. It's impossible to use this (reliably) for anything else, unfortunately; there's no way to distinguish between a filename "<stdin>" and sys.stdin, for example.

如果您只想能够识别用户消息中的文件,那么已经有 file.name。不幸的是,不可能将它(可靠地)用于其他任何事情;例如,无法区分文件名“ <stdin>”和 sys.stdin。

(You really shouldn't have to derive from a builtin class just to add attributes to it; that's just an ugly inconsistent quirk of Python...)

(你真的不应该仅仅为了向它添加属性而从内置类派生;这只是 Python 的一个丑陋的不一致的怪癖......)