I have 100 text files in a folder that I wanna load into a list. I was only able to load one file. how can I load all the files? Here is what I did
with open('varmodel/varmodel_2.var') as f:
varmodel_2 = f.read()
print(varmodel_2)
However, instead of 2, I have from 1 to 100
CodePudding user response:
You can use the glob
module to do just that. It gives you a list of all files/folders in a directory. Here is the code you would use to get a string containing all of the file information:
import glob
string = ""
for filename in glob.glob("*"):
with open(filename, "r") as f:
string = f.read()
print(string)
CodePudding user response:
all_files = []
for dir in glob.glob('varmodel/*'):
with open(dir) as f:
varmodel = f.read(varmodel )
# not sure about txt file content
# it may need preprocess before put to list
all_files.append(varmodel )
print(varmodel)