从文件指针获取文件名

如果我有一个文件指针是否有可能得到的文件名?

fp = open("C:\hello.txt")

有可能用 fp得到 "hello.txt"吗?

133300 次浏览

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.