Python - Get a List of Files in a Directory

Kontext Kontext 0 196 0.19 index 9/4/2022

Code description

This code snippet provides an example of listing files in a directory in the file system using Python. Module os is used.

There are multiple approaches to implement this:

  • os.listdir  - returns both files and directory in a directory. We can check whether the returned items are files using os.path.isfile method.
  • os.walk - generates two lists for each directory it traverse - files and directories. The walk can be used to retrieve all the sub folders recursively.

 

Sample output:

['F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209020059.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209020429.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209020710.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209020921.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209021147.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209021357.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209021637.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209022007.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209030218.log', 'F:\\Projects\\kontext-logs\\RawLogs-0\\c716eb-202209030818.log']

Reference: os — Miscellaneous operating system interfaces

Code snippet

    import os
    from os.path import *
    
    path = r"F:\Projects\kontext-logs\RawLogs-0"
    files = [join(path,item) for item in os.listdir(path) if isfile(join(path,item))]
    print(files)
    
    from os import walk
    filenames = [join(path, item) for item in next(walk(path), (None, None, []))[2]]
    print(filenames)
python

Join the Discussion

View or add your thoughts below

Comments