如何获取打开文件的名称?

时间:2021-10-19 16:05:02

I'm trying to store in a variable the name of the current file that I've opened from a folder.

我正在尝试在变量中存储我从文件夹中打开的当前文件的名称。

How can I do that? I've tried cwd = os.getcwd() but this only gives me the path of the folder, and I need to store the name of the opened file.

我怎样才能做到这一点?我试过cwd = os.getcwd()但这只给了我文件夹的路径,我需要存储打开文件的名称。

Can you please help me?

你能帮我么?

3 个解决方案

#1


40  

Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('generic.png','r')
>>> f.name
'generic.png'

#2


40  

One more useful trick to add. I agree with original correct answer, however if you're like me came to this page wanting the filename only without the rest of the path, this works well.

添加一个更有用的技巧。我同意原始的正确答案,但是如果你像我一样来到这个页面只想要文件名而没有剩下的路径,这很有效。

>>> f = open('/tmp/generic.png','r')
>>> f.name
'/tmp/generic.png'
>>> import os
>>> os.path.basename(f.name)
'generic.png'

#3


4  

Maybe this script is what you want?

也许这个脚本是你想要的?

import sys, os
print sys.argv[0]
print os.path.basename(sys.argv[0])

When I run the above script I get;

当我运行上面的脚本时,我得到了;

D:\UserData\workspace\temp\Script1.py
Script1.py

#1


40  

Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('generic.png','r')
>>> f.name
'generic.png'

#2


40  

One more useful trick to add. I agree with original correct answer, however if you're like me came to this page wanting the filename only without the rest of the path, this works well.

添加一个更有用的技巧。我同意原始的正确答案,但是如果你像我一样来到这个页面只想要文件名而没有剩下的路径,这很有效。

>>> f = open('/tmp/generic.png','r')
>>> f.name
'/tmp/generic.png'
>>> import os
>>> os.path.basename(f.name)
'generic.png'

#3


4  

Maybe this script is what you want?

也许这个脚本是你想要的?

import sys, os
print sys.argv[0]
print os.path.basename(sys.argv[0])

When I run the above script I get;

当我运行上面的脚本时,我得到了;

D:\UserData\workspace\temp\Script1.py
Script1.py