How to get files from directories in Python
I have a list of directories (their ab开发者_开发问答solute path). Each directory contains a certain number of files. Of these files I want to get two of them from each directory. The two files I want have some string pattern in their name, for the sake of this example the strings will be 'stringA', 'stringB'.
So what I need is a list of tuples. Each tuple should have a stringA
file and a stringB
file in it. There should be one tuple per directory. Each directory is guaranteed to have more than 2 files and is guaranteed to have only one stringA
and one stringB
file.
What is the most efficient way to do this? Maybe using a list generator?
Edit:
An example:
dirs = ['/dir1', '/dir2', '/dir3']
result = [('/dir1/stringA.txt', '/dir1/stringB.txt'), ('/dir2/stringA.txt', ...) ...]
The input is directories (a list of directories) and the output should be the result (a list of tuples).
See if this works for you:
import glob
result = zip(sorted(glob.glob('/dir/*stringA*')), sorted(glob.glob('/dir/*stringB*')))
精彩评论