223k views
5 votes
Develop an application that uses file and directory access to encode their structure in a JSON file given a root directory. Create a python application that given a command-line argument of a root directory, it will traverse that directory and all subdirectories, saving into a file called struct.dat the JSON representation of the hierarchy of files and directory discovered. Use the following information to name file and directory in the JSON representation of the file/dir hierarchy, "File", "Dir", "SubDir" This file should be stored in the location that the program is executed and should override the file if it already exist.

1 Answer

4 votes

Answer:

Check the explanation

Step-by-step explanation:

import sys

import os

import json

## This returns a walk() object,

## Starting in the current directory

## Which will return a tuple for every folder in it

x = os. walk(".") # Current directory

#x = os.walk(sys. argv[1]) # Directory specified by command-line argument

d = {}

print("Our walk object's output:")

for thing in x:

print(thing)

# As you will see, this prints out a 3-tuple for each folder:

# thing[0] contains the directory name of the folder

# thing[1] contains a list of all subfolders

# thing[2] contains a list of all files

# We will now encode this information as a dictionary

# This does not meet your assignment's formatting specifications

# Getting this right so that it puts the information into the dict the way your guy wants

# is in fact the hard part

# Instead of just having it all in one dict,

# he wants the json nested, which means he needs nested dict

# Each folder needs to be a dict, and needs to contain dicts for each of its subfolders

# That's not what we're doing right now

x = os.walk(".") # or sys.argv[1] if you want to take one command line argument

for thing in x:

d[thing[0]] = (thing[1], thing[2])

print("Our dict:")

print(d)

# Now that this is all in a dict we can json .dump it

json .dump(d, f) # Write data to the file

print("Printing json, this is what gets put into the file:")

print(json.dumps(d)) # Dump the data into a string so we can look at it

User Alx
by
4.4k points