I'm slowly getting my feet wet in Python but still seem to miss some fundamentals. Especially with lists and dictionaries.
I'm building an importer and there want to check a directory of files for the ones importable for me. Here's a function I'm trying to build for this:
def check_files(directory=os.path.dirname(os.path.realpath(__file__))):
file_number = 0
files = {}
for file in os.listdir(directory):
if os.path.isfile(file):
file_name = os.fsdecode(file)
--> files = {file_number: {'file_name': file_name}}
with open(file_name,'r', encoding='utf-8', errors='ignore') as f:
line = f.readline()
if line == firstline['one']:
--> files = {file_number: {'file_type': 'one'}}
elif line == firstline['two']:
--> files = {file_number: {'file_type': 'two'}}
else:
--> files = {file_number: {'file_type': 'unknown'}}
file_number += 1
return files
As you can see I'm failing to build the dictionary I was thinking of building to carry some file information and return it.
Regarding the dictionary structure I was thinking about something like this:
files = {
0: {'file_name': 'test1.csv', 'file_type': 'one'},
1: {'file_name': 'test2.csv', 'file_type': 'two'}
}
My question is: how do I build the dictionary step by step as I get the values and add new dictionaries into it? I read through quite some dictionary explanations for beginners but they mostly don't handle this multi level case at least not building it step by step.