Reputation: 708
I am working with this list of files in a local directory:
docs = ['5d7d3c905deeb7978034cb40.txt','5d7d3c905deeb7978034cb40.txt','5d7d26ae5deeb7978034cab3.txt',
'5d7d268e5deeb7978034cab2.txt','5dac3ad15deeb749fcbbfeab.txt']
If I do this:
for doc in docs:
for txt in open(doc):
I manage to open and read the texts all together. But I want to get each one of them into a distinct variable.
My best solution, for now, is this one:
abstracts = []
for i in range(len(docs)):
for doc in docs:
for txt in open(doc):
txs = [txt] #each text
if txs not in abstracts:
abstracts.append(txs)
I can reach the txs I want by the use of indexes, but I am sure there must be a better way to do this.
Upvotes: 0
Views: 187
Reputation: 36714
globals()["name_of_your_variable"] = my_variable
will assign a variable based on the string you give it. It should work if you str.split(doc, ".")[0]
it first to remove the period.
Upvotes: 0
Reputation: 1380
I would use a dictionary which the keys are the files' names and and values are the files' content
files = {}
for doc in docs:
with open(doc, 'r') as f:
files[doc] = f.read()
Upvotes: 1
Reputation: 17408
Instead use a dict
in python.
import os
content_dict = {}
for f_name in os.listdir("."):
content_dict[f_name.split(".")[0]] = open(f_name).read()
print(content_dict)
Upvotes: 1