1

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

3
  • 1
    What have you tried? Loops, blobs, dictionaries...? Commented Feb 24, 2022 at 23:52
  • Welcome to Stack Overflow. Please read How to Ask and explain what the actual difficulty is. Do you know how to repeat code? Do you know how to create the file names? If you repeat the code for each file name, does that solve the problem? Also, what does this question have to do with Pandas or Numpy? Commented Feb 24, 2022 at 23:57
  • Check out the existing question stackoverflow.com/questions/12497901/…. Commented Feb 25, 2022 at 0:08

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1
    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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.