查找1和只有1个字符,Python

时间:2022-09-01 23:13:08

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

我有很多文件名为file_1,file_2,another_file_1,another_file_2等。

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

如何查找以1和1结尾的文件。

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

目前我正在循环中使用glob函数,例如

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.

问题是这给了我一个名为1,11,21,31等的文件。我只想要文件1一次,文件11一次,依此类推。

1 个解决方案

#1


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

发生这种情况的原因是因为你的通配符匹配器绝对匹配任何东西,直到它找到(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.

如果您知道所有文件的格式都是foo_bar_1.txt,文件编号前面有下划线,则可以使用此匹配器:glob.glob('* _'+ str(i + 1)+'。txt' )它只会返回你想要的东西。

#1


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

发生这种情况的原因是因为你的通配符匹配器绝对匹配任何东西,直到它找到(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.

如果您知道所有文件的格式都是foo_bar_1.txt,文件编号前面有下划线,则可以使用此匹配器:glob.glob('* _'+ str(i + 1)+'。txt' )它只会返回你想要的东西。