如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
但即使在导入os时,我也无法将其称为path.basename。是否可以直接将其称之为basename?
导入os,然后使用os.path.basename
导入os并不意味着你可以在不引用os的情况下使用os.foo。
其他回答
>>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
hemanth
我没有仔细看,但我没有看到任何人使用正则表达式解决这个问题。
我将问题解释为“给定路径,返回不带扩展名的基名称。”
e.g.
“path/to/file.json”=>“文件”
“path/to/my.file.json”=>“my.file”
在Python 2.7中,我们仍然没有pathlib。。。
def get_file_name_prefix(file_path):
basename = os.path.basename(file_path)
file_name_prefix_match = re.compile(r"^(?P<file_name_pre fix>.*)\..*$").match(basename)
if file_name_prefix_match is None:
return file_name
else:
return file_name_prefix_match.group("file_name_prefix")
get_file_name_prefix("path/to/file.json")
>> file
get_file_name_prefix("path/to/my.file.json")
>> my.file
get_file_name_prefix("path/to/no_extension")
>> no_extension
您可以通过以下方式制作自己的产品:
>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'
重要提示:如果有多个。在文件名中,只删除最后一个。例如:
/root/dir/sub/file.ext.zip -> file.ext
/root/dir/sub/file.ext.tar.gz -> file.ext.tar
请参阅下面的其他答案来解决这个问题。
>>>print(os.path.splitext(os.paath.basename(“/path/to/file/vrun.txt”))[0])varun
这里/path/to/file/vrun.txt是文件的路径,输出为varun
import os
filename, file_extension =os.path.splitext(os.path.basename('/d1/d2/example.cs'))
文件名为“example”文件扩展名为“.cs”
'