如何找到文件然后在Python中循环它们?

时间:2015-07-07 20:04:22

标签: python file search find

我有一个包含以下代码的Bash脚本:

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

您可以看到它以递归方式搜索以.root结尾的文件,然后循环遍历这些文件。我怎么能在Python中做类似的事情?我可以想象用它们的完整路径或相对路径生成各种找到的文件的列表,然后循环遍历该列表,但我不确定如何生成这样的列表。

5 个答案:

答案 0 :(得分:2)

这里有一些代码可以帮助你。

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)

答案 1 :(得分:2)

glob使得这类事情变得非常容易。

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')]

答案 2 :(得分:1)

了解os.walk

非常适合梳理文件系统

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

答案 3 :(得分:1)

我从经常使用的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

答案 4 :(得分:1)

以下是我的表现方式:

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()