Search code examples
pythonloopssearchglob

Finding 1 and only 1 character, Python


I have many files named file_1, file_2, another_file_1, another_file_2 etc.

How can I find the files which end with 1 and only 1.

At the moment I'm using the glob function in a loop, such as

for i in range(len(number_of_files)):
    files = glob.glob("*" + str(i+1) + ".txt")

The problem is that this gives me the files called 1, 11, 21, 31, etc. I only want file 1 one time, file 11 one time and so on.


Solution

  • The reason this is happening is because your wildcard matcher is matching absolutely anything up until it finds (i+1).txt

    If you know all of your files are in the format foo_bar_1.txt where there is an underscore before the file number, you could use this matcher: glob.glob('*_' + str(i + 1) + '.txt') and it would only return what you're looking for.