Press "Enter" to skip to content

Python Program to List Files in a Directory

Here is an example of a Python program to list files in a directory using the wildcard.

List Files in a Directory in Python

The following Python program will list all text files in (f:\code\) directory.

List files in a directory using Python program.

import os
import os.path
import glob

pyfiles = glob.glob('f:\code\*.txt')

name_sz_date = [(name, os.path.getsize(name), os.path.getmtime(name))
                for name in pyfiles]

for r in name_sz_date:
    print(r)

file_metadata = [(name, os.stat(name)) for name in pyfiles]
for name, meta in file_metadata:
    print(name, meta.st_size, meta.st_mtime)

Output:

('f:\code\emails.txt', 26, 1547213695.299731)
('f:\code\email_msg.txt', 3, 1547213709.1189702)
('f:\code\optionDB.txt', 161, 1537253533.6220636)
f:\code\emails.txt 26 1547213695.299731
f:\code\email_msg.txt 3 1547213709.1189702
f:\code\optionDB.txt 161 1537253533.6220636

Process finished with exit code 0

See also: