How can I iterate over files in a given directory?

You can use the os module in Python to iterate over files in a given directory. Here's an example code snippet that demonstrates how to do this:

import os

path = '/path/to/directory'

for filename in os.listdir(path):
    if filename.endswith('.txt'):
        file_path = os.path.join(path, filename)
        with open(file_path) as f:
            print(f.read())

In this example, os.listdir(path) returns a list of all files in the directory specified by path. The for loop then iterates over this list of filenames, and for each file that ends with the '.txt' extension, the open() function is used to open the file, read its contents using the read() method and print it out.

Watch a course Python - The Practical Guide

You can use os.path.join(path, filename) instead of path + '/' + filename to join the path of the directory and the filename, this will work in both Windows and Unix OS. Also, you can use os.path.isfile(file_path) instead of filename.endswith('.txt') to check if the current file is a file and not a directory before opening it.

import os

path = '/path/to/directory'

for filename in os.listdir(path):
    file_path = os.path.join(path, filename)
    if os.path.isfile(file_path):
        with open(file_path) as f:
            print(f.read())