How to read multiple text files from a folder in Python?(Tkinter)


Python is capable of handling files, objects, and creating different applications. We can use Python's extensions and packages to build and develop fully featured applications.

Suppose you want to control the files in your system; then Python provides an OS Module which has system-enabled functionalities to allow you interact with the files in the operating system.

Let us see how we can read multiple text files from a folder using the OS module in Python.

  • Import the OS module in your notebook.

  • Define a path where the text files are located in your system.

  • Create a list of files and iterate over to find if they all are having the correct extension or not.

  • Read the files using the defined function in the module.

Example

# Import the required libraries
import os

# Define the location of the directory
path =r"C:/Users/Sairam/Documents/"

# Change the directory
os.chdir(path)

def read_files(file_path):
   with open(file_path, 'r') as file:
      print(file.read())

# Iterate over all the files in the directory
for file in os.listdir():
   if file.endswith('.txt'):
      # Create the filepath of particular file
      file_path =f"{path}/{file}"

read_files(file_path)

Output

Sample 1
========
Welcome to Tutorialspoint.

You are browsing the best resource for Online Education.

Sample 2
========
A distributed ledger is a type of data structure which resides across multiple computer devices, generally spread across locations or regions.

Distributed ledger technology (DLT) includes blockchain technologies and smart contracts.

While distributed ledgers existed prior to Bitcoin, the Bitcoin blockchain marks the convergence of a host of technologies, including timestamping of transactions, Peer-to-Peer (P2P) networks, cryptography, and shared computational power, along with a new consensus algorithm.

We have two text files in the specified location and the program read the contents of these two files and displayed the text on the console.

Updated on: 18-Jun-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements