3

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

How?

for filename in glob.glob("pc*.txt"):
    global_list.append(filename)
1
  • Side-note: If you're just appending each value to the global list, skip the explicit loop and just do: global_list.extend(glob.glob("pc*.txt")) (or whatever glob pattern you settle on); letting Python perform the work directly in bulk is faster and cleaner than unnecessary explicit loop. Commented Dec 9, 2016 at 3:23

1 Answer 1

5

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"):

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.