Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple files from a same folder using python [duplicate]

I have thousands of text files which I want to read using python. I have successfully read one file and now I am not sure how to read multiple files using loop or any other command

I tried to split the name and type of the file by saving the variable character of the text files saved in a string. e.g I have 3 files named as file_1, file_2, file_3

I took one variable and limit ="1" and conciniate it with the full address of the file. now I want to know how can I access the other two files. provided I don't want to use same line of code multiple times because in reality I have
thousands of files

import os
from os import path
limit1 = "1"
strpath = r"C:/Users/saqibshakeel035/Desktop/SP/text_file_r_w"
print("Your current directory is : %s"  %path.abspath(strpath))
f = open("C:/Users/saqibshakeel035/Desktop/SP/text_file_r_w/file_" + 
limit1 + ".txt", "r")
print(f.read())

This code is working fine for 1 file. Now i want my code to read multile files and later on I will transfer my files to somewhere else.

like image 426
Saqib Shakeel Avatar asked Jan 02 '23 08:01

Saqib Shakeel


1 Answers

You can use glob.glob to access all file paths of the folder, and read each file using for loop.

files = [file for file in glob.glob("../somefolder/*")]
for file_name in files:
    with io.open(file_name, 'rb') as image_file:
        content = image_file.read()
like image 158
JJ.Jones Avatar answered Jan 05 '23 19:01

JJ.Jones