The Wayback Machine - https://web.archive.org/web/20241127060357/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
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next 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
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
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 files between directories. Method 1 : Using shutil.c
2 min read
How to List all Files in a Directory using CMD?
If you're working with the Command Prompt in Windows and need to know how to list files in a directory using CMD, you're in the right place. The Command Prompt, often referred to as CMD, is a powerful tool for navigating and managing your file system. This article will show you how to use simple CMD commands to list all files in a directory, giving
5 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
How to iterate over files in directory using Python?
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory. Below are the various approaches by using which one can iterate over files in a directory using python: M
2 min read
How to read all excel files under a directory as a Pandas DataFrame ?
In this article, we will see how to read all Excel files in a folder into single Pandas dataframe. The task can be performed by first finding all excel files in a particular folder using glob() method and then reading the file by using pandas.read_excel() method and then displaying the content. Approach:Import necessary python packages like pandas,
1 min read
How to Copy files from one Directory to another using CMD?
The Command Prompt (CMD) provides a quick and effective approach to handle your data when working with files in Windows. This tutorial will walk you through the process of using CMD to copy files from one directory to another step-by-step. Anyone wishing to transfer files using the command line will find the CMD copy command to be a useful tool as
4 min read
Python - Copy Directory Structure Without Files
In this article, we will discuss how to copy the directory structure with files using Python. For example, consider this directory tree: We have a folder named "base" and inside have we have one folder named "Structure". "Structure" has some folders inside which also contain some files. Now we have to copy all the folders of "Structure" to a folder
3 min read
Python - Get list of files in directory sorted by size
In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows: Using os.listdir() functionUsing glob() functions Method 1: Using o
3 min read
Python - List files in directory with extension
In this article, we will discuss different use cases where we want to list the files with their extensions present in a directory using python. Modules Usedos: The OS module in Python provides functions for interacting with the operating system.glob: In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The pa
3 min read
Python - Get list of files in directory with size
In this article, we are going to see how to extract the list of files of the directory along with its size. For this, we will use the OS module. OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent f
9 min read
Python - List Files in a Directory
Sometimes, while working with files in Python, a problem arises with how to get all files in a directory. In this article, we will cover different methods of how to list all file names in a directory in Python. Table of Content What is a Directory in Python?How to List Files in a Directory in PythonList Files in a Directory Using Os ModuleUsing os.
9 min read
How to merge multiple excel files into a single files with Python ?
Normally, we're working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one w
4 min read
Why are there two folders - Program Files and Program Files (x86) in 64-bit Windows OS?
Have you ever wondered why you have two different Program Files (Program Files and Program Files (x86)) on your 64-bit Windows Operating System? Well, you will get the answer to this question by going through this article. Earlier on, the Windows OS has 32-bit version only. If you are still using a 32-bit of Windows today, you will notice that you
3 min read
Extract all the URLs that are nested within <li> tags using BeautifulSoup
Beautiful Soup is a python library used for extracting html and xml files. In this article we will understand how we can extract all the URLSs from a web page that are nested within <li> tags. Module needed and installation:BeautifulSoup: Our primary module contains a method to access a webpage over HTTP.pip install bs4Requests: used to perfo
4 min read
Attaching a Decorator to All Functions within a Class in Python
Decorators in Python allow us to add extra features to functions or methods of class without changing their code. Sometimes, we might want to apply a decorator to all methods in a class to ensure they all behave in a certain way. This article will explain how to do this step by step. Applying Decorators to Class MethodsTo apply a decorator to all m
2 min read
Copy a directory recursively using Python (with examples)
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the desti
5 min read
Get parent of current directory using Python
In Python, OS module is used to interact with the operating system. It comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. OS module provides various ways for getting the parent di
4 min read
Delete an entire directory tree using Python | shutil.rmtree() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories. shutil.rmtree() is used to delete an entire directory tree, path must point to a directory (but not
3 min read
Finding the largest file in a directory using Python
In this article, we will find the file having the largest size in a given directory using Python. We will check all files in the main directory and each of its subdirectories. Modules required: os: The os module in Python provides a way of using operating system dependent functionality. OS module is available with Python's Standard Library and does
2 min read
How to Create Directory If it Does Not Exist using Python?
In this article, We will learn how to create a Directory if it Does Not Exist using Python. Method 1: Using os.path.exists() and os.makedirs() methods Under this method, we will use exists() method takes path of demo_folder as an argument and returns true if the directory exists and returns false if the directory doesn't exist. makedirs() method is
2 min read
Typical directory structure for running tests using unittest in Python
In this article, we will take a look at the typical directory structure for running tests using unittest in Python. What is the unittest module in Python? The unittest module is a built-in Python library that is used for testing the functionality of individual units of source code. It is a powerful tool that allows developers to write and run repea
7 min read
How to Print Files from any Mobile Phone using Dropbox?
Printing files directly from your mobile phone can be incredibly convenient, especially when using a cloud storage service like Dropbox. With Dropbox mobile printing, you can easily access and print your documents from anywhere, without needing to transfer them to a computer first. This guide will walk you through the steps on how to print files fr
5 min read
How to List all Files and Directories in FTP Server using Python?
FTP ( File Transfer Protocol ) is set of rules that computer follows to transfer files across computer network. It is TCP/IP based protocol. FTP lets clients share files. FTP is less secure because of files are shared as plain text without any encryption across the network. It is possible using python to retrieve list of file and directories from F
2 min read
three90RightbarBannerImg