本文介绍了正则表达式,glob,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹,包含许多文件.有一个包含pc_0.txt,pc_1.txt,...,pc_699.txt的组.我想选择pc_200->到pc_699.txt之间的所有文件

I have a folder, contains many files.There is a group contains pc_0.txt,pc_1.txt,...,pc_699.txt.I want to select all files beetween pc_200 - > to pc_699.txt

如何?

for filename in glob.glob("pc*.txt"):
    global_list.append(filename)

推荐答案

对于这种特定情况,glob已经支持您所需要的内容(请参阅 fnmatch全局通配符文档).您可以这样做:

For this specific case, glob already supports what you need (see fnmatch docs for glob wildcards). You can just do:

for filename in glob.glob("pc[23456]??.txt"):

如果您需要更具体地说明两个结尾字符是数字(某些文件中可能包含非数字字符),则可以将?替换为[0123456789],但是否则,我会找到分心一点.

If you need to be extra specific that the two trailing characters are numbers (some files might have non-numeric characters there), you can replace the ?s with [0123456789], but otherwise, I find the ? a little less distracting.

在更复杂的情况下,您可能被迫诉诸正则表达式,并且可以在此处执行以下操作:

In a more complicated scenario, you might be forced to resort to regular expressions, and you could do so here with:

import re

for filename in filter(re.compile(r'^pc_[2-6]\d\d\.txt$').match, os.listdir('.')):

但是考虑到通配符通配符已经足够好用了,您现在还不需要大手笔.

but given that glob-style wildcards work well enough, you don't need to break out the big guns just yet.

这篇关于正则表达式,glob,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:23