stack overflow
stack overflow

Reputation: 7

Read multiple files and store filename as key and value as the contents of the file in python dictonary

I currently have a list with the following filenames [file1, file2] I want to read each files by iterating through the list and read the contents of the file into dictionary

So I am trying to create dictionary with key and value as :

thisisdict={ "file1" : "abcdefgh", "file2" :" defssfifj"}

I am able to read and store values of each individuals files but unsure when multiple filenames are to iterated and opened and read.

Upvotes: 0

Views: 364

Answers (2)

0x0fba
0x0fba

Reputation: 1620

thisisdict = { f: open(f).read() for f in ["file1", "file2"]}

Upvotes: 1

babis21
babis21

Reputation: 1881

This should be fairly easy, if I understand your requirement right.

my_dict = {}
for filename in ['file1.txt', 'file2.txt']:
    with open(filename, 'r') as f:
        _t = f.read()
        my_dict.update({filename: _t})

Of course, this is a simple solution for small files, this can be done better if you have massive files etc.

Upvotes: 0

Related Questions