Reputation: 964
Is it possible in python to open a file that contain certain characters or patterns that other files in that directory for example i have 5 files in a directory:
file1.py file2.py file2_0.out file_1.out file1.out file2.out
I would like to only open the files that end with "_0.out" and "_1.out" I am not familiar with regex in python or if it can be used. Any ideas?
Upvotes: 0
Views: 115
Reputation: 117946
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski
That being said, regex
might be overkill for this. The str
class has a endswith
method that you can use in a list comprehension to handle this.
>>> l = ['file1.py', 'file2.py', 'file2_0.out', 'file_1.out', 'file1.out', 'file2.out',]
>>> [i for i in l if i.endswith(('_0.out','_1.out'))]
['file2_0.out', 'file_1.out']
Upvotes: 4