Search code examples
pythondictionarypathsizefile-extension

Python program to produce dictionary of file names, extensions, path, creation times, and sizes, and output them to a json file


import os, json, time

path = "C:\\Users\\Marius\\Desktop\\homework" #se defineste adresa

with os.scandir(path) as listOfEntries:
    for item in listOfEntries:
        
        data={}
        if item.is_file():
            filename_ext=os.path.splitext(item)
            size=(os.path.getsize(item))
            creation=(time.ctime(os.path.getctime(item)))
            extension=(os.path.splitext(os.path.basename(item))[1])
            
            if filename_ext not in data:
                data[item.path] = {'name': item.name, 'path': path, 'extension': extension, 'creation': creation, 'size': size}
          
print(data)
        
j_data = json.dumps(data, indent=4)

with open('files.json', 'w') as f:
    json.dump(data, f, indent=4)

I cannot figure it out. Any help would be appreciated.

I tried to make a python file to generate the results needed, but I need them to be as an output JSON file.

I want the results to be as an output to files.JSON, something like the following result, but with all the files from that specific folder:

{
     "C:\\Users\\Marius\\Desktop\\homework\\test.py": {
          "name": "test.py",
          "path": "C:\\Users\\Marius\\Desktop\\homework",
          "extension": ".py",
          "creation": "Sat Dec 26 08:39:59 2020",
          "size": 733
     }
}

Solution

  • Solved with:

    import os, json, time
    
    path = "C:\\Users\\Marius\\Desktop\\homework"
    
    data={}
    with os.scandir(path) as listOfEntries:
        for item in listOfEntries:
                filename_ext=os.path.splitext(item)
                size=(os.path.getsize(item))
                creation=(time.ctime(os.path.getctime(item)))
                extension=(os.path.splitext(os.path.basename(item))[1])
                if item.is_file():
                    if filename_ext not in data:
                        data[item.path] = {'name': item.name, 'path': path, 'extension': extension, 'creation': creation, 'size': size}
    print(data)
            
    j_data = json.dumps(data, indent=4)
    
    with open('files.json', 'w') as f:
        json.dump(data, f, indent=4)