How to read multiple text files in a folder with python?

Member

by eloise , in category: Python , 2 years ago

 How to read multiple text files in a folder with python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by jaron_crist , 2 years ago

@eloise  You can use os.listdir() to read multiple files:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import os

path = "folder" 

files = os.listdir(path) 

for file in files: 
    with open(path + os.sep + file, 'r') as read_file:
        print(f"File {file} - reading")
        print(read_file.read()) 


Member

by consuelo , a year ago

@eloise 

You can use the os and glob modules in Python to read multiple text files in a folder. Here's an example:

1
2
3
4
5
6
7
8
import os
import glob

folder_path = '/path/to/folder'

for file_path in glob.glob(os.path.join(folder_path, '*.txt')):
    with open(file_path, 'r') as file:
        print(file.read())


This example uses glob.glob to find all the files with the .txt extension in the specified folder_path, and then uses a for loop to open each file, read its contents using the read() method, and print the contents to the console.


You can use other file extension than txt to read other file types like .csv or