visibility 11 comment 0 access_time 21 days ago language English

codePython - Get a List of Files in a Directory

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))]

from os import walk
filenames = [join(path, item) for item in next(walk(path), (None, None, []))[2]]
fork_right Fork
copyright This page is subject to Site terms.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

comment Comments
No comments yet.