我在这样的列表中得到了文件的完整路径:
a = ['home/robert/Documents/Workspace/datafile.xlsx', 'home/robert/Documents/Workspace/datafile2.xls', 'home/robert/Documents/Workspace/datafile3.xlsx']
我想要的是只获取不带扩展名的文件 NAMES,例如:
b = ['datafile', 'datafile2', 'datafile3']
我试过的是:
xfn = re.compile(r'(\.xls)+')
for name in a:
fp, fb = os.path.split(fp)
ofn = xfn.sub('', name)
b.append(ofn)
但结果是:
b = ['datafilex', 'datafile2', 'datafile3x']
最佳答案
您使用的正则表达式是错误的。
(\.xls)+
匹配.xls
形式的字符串,.xls.xls
等。这就是为什么还有一个x
在.xlsx
项目。你要的是\.xls.*
,即.xls
后跟零个或多个任意字符。您实际上并不需要使用正则表达式。 os.path中有专门的方法处理这个:basename和 splitext .
>>> import os.path >>> os.path.basename('home/robert/Documents/Workspace/datafile.xlsx') 'datafile.xlsx' >>> os.path.splitext(os.path.basename('home/robert/Documents/Workspace/datafile.xlsx'))[0] 'datafile'
因此,假设您并不真正关心
.xls
/.xlsx
后缀,您的代码可以像这样简单:>>> a = ['home/robert/Documents/Workspace/datafile.xlsx', 'home/robert/Documents/Workspace/datafile2.xls', 'home/robert/Documents/Workspace/datafile3.xlsx'] >>> [os.path.splitext(os.path.basename(fn))[0] for fn in a] ['datafile', 'datafile2', 'datafile3']
(还要注意 list comprehension 。)
关于python - 如何使用 python 删除文件基名的扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15849521/