Python program to traverse directories and read file information
Asked Answered
R

3

14

I'm just getting started with Python but already have found it much more productive than Bash shell scripting.

I'm trying to write a Python script that will traverse every directory that branches from the directory I launch the script in, and for each file it encounters, load an instance of this class:

class FileInfo:

    def __init__(self, filename, filepath):
        self.filename = filename
        self.filepath = filepath

The filepath attribute would be the full absolute path from root (/). Here's the pseudocode mockup for what I'd like the main program to do:

from (current directory):

    for each file in this directory, 
    create an instance of FileInfo and load the file name and path

    switch to a nested directory, or if there is none, back out of this directory

I've been reading about os.walk() and ok.path.walk(), but I'd like some advice about what the most straightforward way to implement this in Python would be. Thanks in advance.

Responsiveness answered 24/3, 2011 at 15:30 Comment(1)
Where do you want to assign the created object to? This seems to be otherwise trivial.Appetizing
R
17

I'd use os.walk doing the following:

def getInfos(currentDir):
    infos = []
    for root, dirs, files in os.walk(currentDir): # Walk directory tree
        for f in files:
            infos.append(FileInfo(f,root))
    return infos
Refinement answered 24/3, 2011 at 15:37 Comment(1)
Use snake_case instead of CamelCase for Python.Marriage
R
7

Try

info = []
for path, dirs, files in os.walk("."):
    info.extend(FileInfo(filename, path) for filename in files)

or

info = [FileInfo(filename, path)
        for path, dirs, files in os.walk(".")
        for filename in files]

to get a list of one FileInfo instance per file.

Renick answered 24/3, 2011 at 15:36 Comment(0)
P
1

Try it

import os

for item in os.walk(".", "*"):
    print(item)
Patience answered 5/4, 2013 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.