Reputation:
i am looping through a file directory, when i come across a file with some specific text i want to add the file name and modified time to a dictionary, based on my dir i should end up with 7 key, value pairs in my dict.
how do i keep adding key,value pairs to my dict while i loop this dir? thanks
import os
import stat
path =r"C:\Users\Gronk\Downloads"
for file in os.listdir(path):
if 'ConsensusData' in file:
info = os.stat( path+"\\"+file)
t = info.st_atime
x = {}
x.update({file:t})
Upvotes: 0
Views: 49
Reputation: 17322
you can use setdefault method:
x = {}
for file in os.listdir(path):
if 'ConsensusData' in file:
info = os.stat( path+"\\"+file)
t = info.st_atime
x.setdefault(file, t)
Upvotes: 0
Reputation: 88285
Define the dictionary outside the for
loop, and add key
/value
pairs as dict[key]=value
:
x = {}
for file in os.listdir(path):
if 'ConsensusData' in file:
info = os.stat( path+"\\"+file)
t = info.st_atime
x[file] = t
Upvotes: 1