Open In App

How to read multiple text files from folder in Python?

Prerequisite:

Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python.



Approach:

Functions used:



Syntax: os.chdir(path)

Parameters:

  • path: A complete path of directory to be changed to new directory path.

Returns: Doesn’t return any value

Syntax: os.listdir(path)

Parameters:

  • path (optional) : path of the directory

Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list.

Below is the Implementation:

Program:




# Import Module
import os
  
# Folder Path
path = "Enter Folder Path"
  
# Change the directory
os.chdir(path)
  
# Read text File
  
  
def read_text_file(file_path):
    with open(file_path, 'r') as f:
        print(f.read())
  
  
# iterate through all file
for file in os.listdir():
    # Check whether file is in text format or not
    if file.endswith(".txt"):
        file_path = f"{path}\{file}"
  
        # call read text file function
        read_text_file(file_path)

Output:

Article Tags :