0

I currently know how to create a list of files that are in the current directory using:

files = [os.path.join(root, name)
         for root, dirs, files in os.walk(os.getcwd())
         for name in files
         if name.endswith(".fastq")]

However, I would like the list 'files' to contain list of folders and within the list of folders, the file names.

Thank you in advance.

Labrat
  • 105
  • 10
  • 1
    You mean a list of lists, where each sublist contais the matches from one specific directory? Or what? – tripleee Jun 23 '16 at 17:48

1 Answers1

1

Is this what you are looking for?

import os
import json
file_list = dict()
for root, dirs, files in os.walk(os.getcwd()):
    for name in files:
        if name.endswith('.fastq'):
            if root not in file_list:
                file_list[root] = [name]
            else:
                file_list[root].append(name)
print json.dumps(file_list, indent=4)

Output:

{
    "/home/user/": [
        "1000.fastq", 
        "1001.fastq", 
        ...
        "1010.fastq"
    ]
}

Ellipsis used to indicated skipped values.

  • The JSON part is rather outside the scope of this question. Just build the dict, and let the OP take it from there. – tripleee Jun 24 '16 at 07:56
  • I like to put complete programs in my answers. I also like to use `json.dumps` to format the output in my answers to make them easier to read. I think it will be obvious to the OP that the answer can be customized to fit the need. –  Jun 24 '16 at 14:06