Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse through the files in a directory?

Tags:

python

I have a directory logfiles. I want to process each file inside this directory using a Python script.

for file in directory:
      # do something

How do I do this?

like image 949
Bruce Avatar asked Feb 07 '11 06:02

Bruce


People also ask

How do I iterate through the files in a directory in Java?

1 Answer. You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

How do you loop through all the files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).


2 Answers

With os.listdir() or os.walk(), depending on whether you want to do it recursively.

like image 106
Ignacio Vazquez-Abrams Avatar answered Sep 18 '22 14:09

Ignacio Vazquez-Abrams


In Python 2, you can try something like:

import os.path

def print_it(x, dir_name, files):
    print dir_name
    print files

os.path.walk(your_dir, print_it, 0)

Note: the 3rd argument of os.path.walk is whatever you want. You'll get it as the 1st arg of the callback.

In Python 3 os.path.walk has been removed; use os.walk instead. Instead of taking a callback, you just pass it a directory and it yields (dirpath, dirnames, filenames) triples. So a rough equivalent of the above becomes

import os

for dirpath, dirnames, filenames in os.walk(your_dir):
    print dirpath
    print dirnames
    print filenames
like image 41
luc Avatar answered Sep 19 '22 14:09

luc