简体   繁体   中英

Moving into a directory without knowing its name

Im a noob to python and I am trying to complete this simple task. I want to access multiple directories one by one that are all located inside one directory. I do not have the names of the multiple directories. I need to enter into the directory, combine some files, move back out of that directory, then into the next directory, combine some files, move back out of it, and so on........ I need to make sure I dont access the same directory more than once.

I looked around and tried various commands and nothing yet.

try using something like the following piece of code.:

import os, fnmatch

def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)

                yield filename

use it something like this:

for filename in find_files('/home/', '*.html')
    # do something

Sometimes I find glob to be useful:

from glob import glob
import os

nodes = glob('/tmp/*/*')

for node in nodes:
    try:
        print 'now in directory {}'.format(os.path.dirname(node))
        with open(node, 'r') as f:
            # Do something with f...
            print len(f.read())
    except IOError:  # Because node may be a directory, which we cannot 'open'
        continue

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