Home > database >  Read multiple files and store filename as key and value as the contents of the file in python dicton
Read multiple files and store filename as key and value as the contents of the file in python dicton

Time:11-12

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.

CodePudding user response:

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.

CodePudding user response:

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