问题:从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
此处的键是代表打开文件name
的f
对象的属性。你得到这样的:
>>> 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
而且,如果您只想获取目录名称,而无需使用它附带的文件名,则可以使用os
Python模块按照以下常规方式进行操作。
>>> 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)