python解析文件名进行分类_Python:解析和分组目录中的文件名

博主有MATLAB和C经验但刚接触Python,需解析特定目录下文件名,按项目、主题、会话分组并操作。给出了初步尝试代码,最后解决方案是用defaultdict创建含列表的字典,实现会话名和文件名的映射。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm pretty new to python, but I have lots of experience with MATLAB & C.

What I need to do it parse the filenames of files in a particular directory, separate them into groups according to the fields within the file names, and perform operations within these groups.

Specifically, the filenames are:

PROJECT-x-SUBJECT-x-SESSION-x-TYPE.extension

where that '-x-' has been purposely inserted as the field divider. I need to do operations on every group of files that shares the same PROJECT-x-SUBJECT-x-SESSION component.

_______My best attempt follows:________

I can parse each of the files one at a time by:

dirList=os.listdir(directory)

for fname in dirList:

# kill extension

ext = os.path.splitext(fname)

# get the 4 fields

labels=ext[0].split('-x-')

PROJECT_list.append(labels[0])

SUBJECT_list.append(labels[1])

...

... which reflects this only idea I have had on how to organize this stuff: by creating 4 lists and appending to them for each filename.

Then with my 4 (ordered?) lists, I could then call something like:

from collections import Counter

c=Counter(SESSION_list)

list(c)

Then at least I have a unique list of SESSION names

Suggestions? I could go on, but since I really just need a starting point, I think that this is sufficient.

Thanks, guys.

解决方案

You can use defaultdict to make a dictionary that contains lists:

from collections import defaultdict

groups = defaultdict(list)

for filename in os.listdir(directory):

basename, extension = os.path.splitext(filename)

project, subject, session, ftype = basename.split('-x-')

groups[session].append(filename)

Now, groups contains a mapping between session names and filenames.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值