文件对象的绝对路径 [英] Absolute path of a file object

查看:73
本文介绍了文件对象的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前已经在StackOverflow上进行了讨论-我试图找到一种找到文件对象绝对路径的好方法,但是我需要它对os.chdir()具有鲁棒性,因此不能使用

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

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)

那么一个人可以做

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

这样做有任何风险吗?

推荐答案

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

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

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

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.

因此,在操作系统没有这样的保证的情况下,在整个过程的生命周期中依赖相同的路径是一个坏主意.

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

这篇关于文件对象的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆