问题:从Python中的打开文件获取路径

如果我有一个打开的文件,是否有os调用以字符串的形式获取完整路径?

f = open('/Users/Desktop/febROSTER2012.xls')

f,我将如何获得"/Users/Desktop/febROSTER2012.xls"

If I have an opened file, is there an os call to get the complete path as a string?

f = open('/Users/Desktop/febROSTER2012.xls')

From f, how would I get "/Users/Desktop/febROSTER2012.xls" ?


回答 0

此处的键是代表打开文件namef对象的属性。你得到这样的:

>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'

有帮助吗?

The key here is the name attribute of the f object representing the opened file. You get it like that:

>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'

Does it help?


回答 1

我有完全相同的问题。如果使用相对路径,则os.path.dirname(path)将仅返回相对路径。os.path.realpath可以解决这个问题:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

回答 2

而且,如果您只想获取目录名称,而无需使用它附带的文件名,则可以使用osPython模块按照以下常规方式进行操作。

>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'

这样,您就可以掌握目录结构。

And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os Python module.

>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'

This way you can get hold of the directory structure.


回答 3

您也可以这样获得它。

filepath = os.path.abspath(f.name)

You can get it like this also.

filepath = os.path.abspath(f.name)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。