Os Module Quick Guide

How to list all files in a folder

To list all the files in a folder using the os module in Python, you can use the os.listdir() function. This function returns a list of all the files and directories in the specified folder.

Here’s an example code snippet that demonstrates how to use the os module to list all the files in a folder:

import os

# Specify the folder path
folder_path = '/path/to/folder'

# Get a list of all the files in the folder
file_list = os.listdir(folder_path)

# Loop through each file in the file list
for file_name in file_list:
    # Print the file name
    print(file_name)

In the above code, we first specify the folder path using a string. We then use the os.listdir() function to get a list of all the files and directories in the folder. We then loop through each file in the file list and print the file name to the console.

Note that you can replace '/path/to/folder' with the actual path to the folder you want to list the files of. Also, note that the os.listdir() function returns both files and directories in the specified folder. If you want to list only the files, you can add a condition to check if the item in the list is a file using the os.path.isfile() function.

How to check if a path is a file or not ?

we use the os.path.isfile() function to check if the path_to_check is a file or not. If the path is a file, we print a message saying that it is a file. Otherwise, we print a message saying that it is not a file.

import os

# Specify the path to check
path_to_check = '/path/to/file'

# Check if the path is a file
if os.path.isfile(path_to_check):
    print(f"{path_to_check} is a file")
else:
    print(f"{path_to_check} is not a file")