Python 从文件指针获取文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15225557/
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-08-18 19:33:41 来源:igfitidea点击:
Get filename from file pointer
提问by arjun
If I have a file pointer is it possible to get the filename?
如果我有文件指针,是否可以获取文件名?
fp = open("C:\hello.txt")
Is it possible to get "hello.txt"using fp?
可以"hello.txt"使用fp吗?
采纳答案by mgilson
You can get the path via fp.name. Example:
您可以通过fp.name. 例子:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basenameif you want onlythe file name:
os.path.basename如果您只需要文件名,则可能需要:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
文件对象文档(适用于 Python 2)在这里。

