简体   繁体   中英

for every file in every directory python

I wanted to make a program, that searches for a specific file/extension or checks the file itself. Im starting in 'C:\\', and I want to appeal the process on every file in subdirectories, so walk over whole pc files. I used os.listdir() before, but it didnt work, will this code work?

for path, directories, files in os.walk('C:\\'):
        for file in files:
                try:
                       #finding the file
                except: pass

Suggest me more ways please...

all functions return file paths

this will find the first match:

import os

def find(name, path="C:\\"):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

And this will find all matches:

def find_all(name, path="C:\\"):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result

And this will match a pattern:

import os
import fnmatch

def find(pattern, path="C:\\"):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

This code will work and it will be more efficient than os.listdir() if and only if you want to search everywhere. If you don't want anything else besides "just searching the file", os.walk() is the best option.

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