Reputation: 23
I want to open multiple files in Python and assign them to a dictionary as values.
I can open each of them with open()
function but what if I had like 1000 files?!
Its something like this but I need a loop to open these files and assign them to documents dictionary! I wonder if anyone could help me.
f1 = open('doc1.txt', 'r').read()
f2 = open('doc2.txt', 'r').read()
f3 = open('doc3.txt', 'r').read()
f4 = open('doc4.txt', 'r').read()
f5 = open('doc5.txt', 'r').read()
f6 = open('doc6.txt', 'r').read()
f7 = open('doc7.txt', 'r').read()
f8 = open('doc8.txt', 'r').read()
f9 = open('doc9.txt', 'r').read()
f10 = open('doc10.txt', 'r').read()
documents = {'doc1':f1, 'doc2':f2, 'doc3':f3, 'doc4':f4, 'doc5':f5, 'doc6':f6, 'doc7':f7, 'doc8':f8, 'doc9':f9, 'doc10':f10}
Upvotes: 0
Views: 456
Reputation:
You can use a for-loop like so:
documents = {}
for i in range(1, 11):
i = str(i)
with open('doc' + i + '.txt') as f: # This closes the files when done.
documents['doc' + i] = f.read()
Keep in mind though that the documents
dictionary will consume a lot of memory if the files are large. It would probably be best to open and read them one at a time instead of all at once.
Upvotes: 3