简体   繁体   中英

How can I find files and then loop over them in Python?

I have a Bash script that contains the following code:

merge_ROOT_files(){
    output_file=""$(date -u "+%Y-%m-%dT%H%M%S")"Z_merged.root"
    list_of_files="$(find . -name \*.root -type f)"
    command="hadd "${output_file}""
    for current_file in ${list_of_files}; do
        echo "found ROOT file "${current_file}""
        command=""${command}" "${current_file}""
    done
    echo "merge ROOT files to output ROOT file "${output_file}""
    echo "merge command: ${command}"
    eval "${command}"
}

merge_ROOT_files

You can see that it searches recursively for files that end in .root and then it loops over those files. How could I do something similar in Python? I could imagine generating a list of the various found files with their full or relative paths and then looping over that list, but I'm not sure how to generate such a list.

Here's a bit of code that should get you going.

import os
import re

searchdir = '.'
ext_rx = '\.root$'

filelist = []

for root, dir, files in os.walk(searchdir):
    for file in files:
        if re.search(ext_rx, file):
            filelist.append(os.path.join(root, file))

for file in filelist:
    print(file)

glob makes it very easy to do this type of thing.

import os
import glob

# Get full path for .root files
root_files = glob.glob('/your_path/*.root')

# Only get root file names
root_file_names = [os.path.basename(f) for f in glob.iglob('/your_path/*.root')]

Look into os.walk

It is very good for combing through the file system

http://www.tutorialspoint.com/python/os_walk.htm

I have extracted this code from my frequently used utils

import os
import os.path

def flatten( seq ) :
  res = []
  for item in seq :
    if ( isinstance( item, ( tuple, list ) ) ) :
      res.extend( flatten( item ) )
    else:
      res.append( item )
  return res


def get_roots( path ) :
    """Get a list of .root files in a given directory.
    """
    rootfiles2 = []
    os.listdir( path )
    for root, dirs, files in os.walk( path, topdown=True ) :
        #print ( 'root =', root, ', dirs =', dirs, ', files =', files )
        print ( 'root =', root )
        print ( 'dirs =', dirs )
        print ( 'files =', files )
        # Get only .root files
        rootfiles2.append( [ root + '/' + file for file in files if ( file.split('.')[-1] == 'root' ) ] )
    rootfiles = list( flatten( rootfiles2 ) )
    return rootfiles

And here's how I'd do it:

import os
import fnmatch
import subprocess
import datetime


def merge_ROOT_files():
    output_file = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H%M%SZ_merged.root")

    root_files = [
        os.path.join(root, filename)
        for root, dirs, files in os.walk('.')
        for filename in files
        if fnmatch.fnmatch(filename, '*.root')
    ]

    # Remove 'echo' when you want to go live.
    subprocess.check_call(['echo', 'hadd', output_file]+root_files)

if __name__ == "__main__":
    merge_ROOT_files()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM