如何从完整的文件名列表中删除文件扩展名? [英] How can I strip the file extension from a list full of filenames?
问题描述
我正在使用以下方法来获取包含名为tokens
的目录中的所有文件的列表:
I am using the following to get a list with all the files inside a directory called tokens
:
import os
accounts = next(os.walk("tokens/"))[2]
输出:
>>> print accounts
['.DS_Store', 'AmieZiel.py', 'BrookeGianunzio.py', 'FayPinkert.py', 'JoieTrevett.py', 'KaroleColinger.py', 'KatheleenCaban.py', 'LashondaRodger.py', 'LelaSchoenrock.py', 'LizetteWashko.py', 'NickoleHarteau.py']
我想从此列表中的每个项目中删除扩展名.py
.我设法使用os.path.splitext
分别进行了此操作:
I want to remove the extension .py
from each item in this list. I managed to do it individually using os.path.splitext
:
>>> strip = os.path.splitext(accounts[1])
>>> print strip
('AmieZiel', '.py')
>>> print strip[0]
AmieZiel
我确定自己在做些过分的事情,但是我想不出一种通过for循环从列表中所有项目中去除文件扩展名的方法.
I'm sure I'm overdoing things, but I can't figure out a way to strip the file extension from all the items in the list with a for-loop.
正确的方法是什么?
推荐答案
您实际上可以使用但是,如果您想要/需要一个for循环,则等效代码为:
But if you want/need a for-loop, the equivalent code would be:
lst = []
for x in accounts:
lst.append(os.path.splitext(x)[0])
也请注意,我保留了os.path.splitext(x)[0]
部分.这是Python中从文件名中删除扩展名的最安全方法. os.path
模块中没有专门用于此任务的功能,因此无法使用str.split
手工制作解决方案,否则容易出错.
Notice too that I kept the os.path.splitext(x)[0]
part. This is the safest way in Python to remove the extension from a filename. There is no function in the os.path
module dedicated to this task and handcrafting a solution with str.split
or something would be error prone.
这篇关于如何从完整的文件名列表中删除文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!