Is there a way to read n text files in a folder and store as n str variable?

252 Views Asked by At

I want to read N number of text files in a folder and store them as N number of variables. Note, input will just be folder path and number of text files in it may vary(so n).

Manually i do it like below code, which needs to be completely changed:

import os
os.chdir('C:/Users/Documents/0_CDS/fileread') # Work DIrectory

#reading file
File_object1 = open(r"abc","r")
ex1=File_object1.read()
File_object2 = open(r"def.txt","r")
ex2=File_object2.read()
File_object3 = open(r"ghi.txt","r")
ex3=File_object3.read()
File_object4 = open(r"jkl.txt","r")
ex4=File_object4.read()
File_object5 = open(r"mno.txt","r")
ex5=File_object5.read()
2

There are 2 best solutions below

4
On BEST ANSWER

You can use python's built-in dict. Here I only give keys of each input as its filename, you can name them in anyway you like.

import os 
path = 'Your Directory'
result_dict = {}
for root, dirs, files in os.walk(path):
    for f in files:
       with open(os.path.join(path,f), 'r') as myfile:
          result_dict[f] = myfile.read()
0
On

If you are not interested in the file names and only the content and there are only files in the dir

from os import listdir


l = [open(f).read() for f in listdir('.')]