The Wayback Machine - https://web.archive.org/web/20240622181340/https://www.geeksforgeeks.org/how-to-print-all-files-within-a-directory-using-python/
Open In App

How to print all files within a directory using Python?

Last Updated : 23 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The OS module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the OS module is one of the standard packages and comes pre-installed with Python.

In this article, we will learn how to print all files within a directory using Python. To do this task we are using the OS module in Python. So, let’s discuss some concepts related to that.

Print All Files Within a Directory Using Python

Below is an example by which we can understand how to print all files in a directory Python. Before moving to the examples, let’s understand the methods and modules used in the given example:

  1. os.listdir(): This method lists all the files and directories within a given directory.
  2. os.path.isfile(): This method to check if a given entity is either a file or a directory.
  3. os.startfile(): This method prints the contents of a given file.

Syntax: os.startfile(path, operation=’open’)

Parameters:

  • path – String containing the path to a given file
  • operation – A string containing one of the following ‘command verbs’
    • ‘print’ – Prints the file pertaining to path
    • ‘edit’ – Opens the file in the default text-editor for editing
    • ‘properties’ – Opens the properties window of the given file
    • ‘find’ – Initiates a search starting from directory mentioned in the path
    • ‘open’ – Opens the application/file pertaining to the path. If the given file is not an executable file, its associated application is opened

Note: Aside from the above modules, you’ll also need a fully functional printer connected to your PC!

Example:

In this example, the provided script is designed to scan through all the files within a specified directory. For each identified file, the program attempts to initiate a print operation using the os.startfile() method. However, if the print operation encounters an error, such as an incompatible file type or missing associated software, the script captures and alerts the user about the issue. The line of code “time.sleep(5)” of the given script is completely optional and is just there to avoid any un-necessary glitching or overlapping of the operations in consecutive files. You can read more about the time.sleep() method.

The demo was done on a Windows 10 machine. The environment is as follows:

  • Path of the directory containing files being printed: “Local Disk (D):/Files”
  • Files in the given directory:
    • Dir – A sample subdirectory
    • File_a.pdf – A sample .pdf file
    • File_b.txt – A sample .txt file
    • File_c.docx – A sample .docx file

Python




# Import libraries
import os
import time
 
# Insert the directory path in here
path = ''
 
# Extracting all the contents in the directory corresponding to path
l_files = os.listdir(path)
 
# Iterating over all the files
for file in l_files:
 
  # Instantiating the path of the file
    file_path = f'{path}\\{file}'
 
    # Checking whether the given file is a directory or not
    if os.path.isfile(file_path):
        try:
            # Printing the file pertaining to file_path
            os.startfile(file_path, 'print')
            print(f'Printing {file}')
 
            time.sleep(5)
        except:
            # Catching if any error occurs and alerting the user
            print(f'ALERT: {file} could not be printed! Please check\
            the associated softwares, or the file type.')
    else:
        print(f'ALERT: {file} is not a file, so can not be printed!')
 
print('Task finished!')


Output:

ezgifcom-resize

Video Demonstration

Note: Since os.startfile() is only available in Windows operating system, so macOS and Linux users might experience some issues while running the script given in the article.



Similar Reads

How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 min read
List all files of certain type in a directory using Python
In python, there are several built-in modules and methods for file handling. These functions are present in different modules such as os, glob, etc. This article helps you find out many of the functions in one place which gives you a brief knowledge about how to list all the files of a certain type in a directory by using Python programming. So the
3 min read
Copy all files from one directory to another using Python
In this article, we will discuss how to copy all files from one directory to another using Python. This can be done using the shutil module. This module can be used in Python to perform operations on files and folders in a directory. Shutil package facilitates the access, movement, and removal of the files between directories. Method 1 : Using shut
2 min read
Getting all CSV files from a directory using Python
Python provides many inbuilt packages and modules to work with CSV files in the workspace. The CSV files can be accessed within a system's directories and subdirectories and modified or edited. The CSV file contents can both be printed on the shell, or it can be saved in the form of the dataframe and played with later. In this article, we will see
3 min read
How to List all Files in a Directory using CMD?
Navigating through files and directories on your computer is a fundamental skill, and the Command Prompt is a powerful tool for managing them efficiently. Whether you're a beginner or an experienced user, knowing how to list all files in a directory using the Command Prompt can save you time and effort. Let's delve into the simple steps to achieve
4 min read
Find all the Files in a Directory with .txt Extension in Python
Directory traversal is a common operation performed by file locator in Operating Systems. The operating system offers elaborate methods for streamlining the search process and the choice to search for a selected filename/extension. This article will teach you how to find all the files in a directory with a .txt (text files) extension using Python.
5 min read
Python List All Files In Directory And Subdirectories
Listing all files in a directory and its subdirectories is a common task in Python, often encountered in file management, data processing, or system administration. As developers, having multiple approaches at our disposal allows us to choose the most suitable method based on our specific requirements. In this article, we will see how we can list a
5 min read
Import the Class within the Same Directory - Python
Python classes are the methods to use object-oriented programming in Python. Python allows to create classes in the main project we are working on or in a new file that only stores the class definition. This article will explain how to import a class within the same directory or subdirectory in Python. For this article, one does not need any Python
4 min read
Remove all empty files within a folder and subfolders in Python
In this article, we will see how to remove all empty files within a folder and its subfolders in Python. We occasionally produce some empty files that are not needed. Here, we will use the below functions/methods to remove all empty files within a folder and its subfolder imported from the OS module and glob module. MethodDescriptionos.walk(path)Ge
4 min read
Check if directory contains files using python
Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(<directory path>) Returns: A list of files pr
3 min read
three90RightbarBannerImg