Python create directory tree

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A Python script to create directories recursively in Linux. No dependencies.

Ishuin/directory_tree

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Creating directories is a hassle, and if you are creating directories within directories, it seems to take forever in completing the tree structure. I was wasting a lot of time in doing this, so I decided to create a simple script that will do all the dirty work for me.

If you are familiar with Python, then you can understand the input as simple dictionary format, if not, understand this as JSON.

dir_structure = < 'Books': < 'Programming_language': < 'Python': < 'Django': <>, 'Flask': <>, 'Python_2.7': <>, 'Python_3': <>, > >, 'CS_subjects': < 'Data_Structure_and_Algorithm': <>, 'Computer_Networks': <>, 'Digital_Logic': <>, "DBMS": <>, > > > 

Input will simply be a file structure, as you can understand in the data. The above input format translates to the directory structure below.

All the directories that are leaf directories (empty directories), will contain blank dictionary as the value of their name. As we move higher in the dictionary, the parent directory will act as the key for the dictionary of directories within the parent directory.

If my explanation doesn’t make sense, just look at the input data and the directory structure.

. ├── Books │ └── Programming_language │ ├── CS_subjects │ │ ├── Computer_Networks │ │ ├── Data_Structure_and_Algorithm │ │ ├── DBMS │ │ └── Digital_Logic │ └── Python │ ├── Django │ ├── Flask │ ├── Python_2.7 │ └── Python_3 . 
  1. Data samples taken here are added by my individual understanding, therefore, the code is designed considering the input provided. If someone could find sample data that could break the code, please update me with the code sample and I will do my best to fix the code according to that data also.
  2. Pull requests are also welcome.

About

A Python script to create directories recursively in Linux. No dependencies.

Источник

Create directory recursively in Python

As a Python developer, I often come across situations where I need to create directories in a recursive manner. Whether it’s organizing files or setting up a directory structure, the ability to create directories programmatically can save a lot of time and effort. In this blog post, I’m thrilled to share with you how to create directories recursively in Python. We’ll explore different techniques and approaches to accomplish this task efficiently. So, let’s dive in and empower ourselves with the knowledge to streamline directory creation in Python!

The os module provides functions for interacting with the Operating System in Python. The os module is standard python utility module. Most Operating System based functionalities are abstracted out in this module and it is provided in a very portable way.

Note — In case of any error or exception, all the functions in the os module raise an OSError . Examples are — trying to create an invalid file name(or folder name), incorrect arguments to the functions, etc.,

Create a single directory in Python using os.mkdir() method

You can create a single directory in python using the os.mkdir() method.

os.mkdir(path, mode = 0o777, *, dir_fd = None) 

The path is the name of the folder either referring to the absolute or relate path depending on how you want it to work.

import os # new folder/dir name new_directory = "debugpointer"  # Parent Directory path # In case of Windows, "D:/" parent_directory = "/home/ubuntu/"  # Setting the path for folder creation path = os.path.join(parent_directory, new_directory)  mode = 0o777  # Create the directory in the path os.mkdir(path, mode) print("Directory %s Created Successfully" % new_directory) 
Directory debugpointer Created Successfully 

Note — FileExistsError is raised when the file already exists in the path. It is advised to handle this error in cases where folder are created often(maybe in a python script that runs every time or the API which creates a folder for some reason, etc.,)

Create directories recursively using in Python using os.makedirs() method

The os.makedirs() method creates a directory recursively in a given path in Python. This means, you can create folders with-in folders (with-in folder and so on. ) easily using the os.makedirs() method.

os.makedirs(path, mode = 0o777, *, dir_fd = None) 

Suppose you want to create 3 folders one within another in the form — debugpointer => python => posts, you can easily achieve this using the os.makedirs() method. Python makes care of creating the recursive folders for you when you just specify the structure of your folders that you need.

import os # new folder/dir name new_directory = "debugpointer/python/posts"  # Parent Directory path # In case of Windows, "D:/" parent_directory = "/home/ubuntu/"  # Setting the path for folder creation path = os.path.join(parent_directory, new_directory)  mode = 0o777  # Create the directory in the path os.makedirs(path, mode) print("Directory %s Created Successfully" % new_directory) 
Directory debugpointer/python/posts Created Successfully 

Note — FileExistsError is raised when the file already exists in the path. It is advised to handle this error in cases where folder are created often(maybe in a python script that runs every time or the API which creates a folder for some reason, etc.,)

In such cases, you can handle other OSError errors as follows and also use exist_ok = True so that the FileExistsError does not appear and it gets suppressed —

import os # new folder/dir name new_directory = "debugpointer/python/posts"  # Parent Directory path # In case of Windows, "D:/" parent_directory = "/home/ubuntu/"  # Setting the path for folder creation path = os.path.join(parent_directory, new_directory)  # Handle the errors try:  # Create the directory in the path  os.makedirs(path, exist_ok = True)  print("Directory %s Created Successfully" % new_directory) except OSError as error:  print("Directory %s Creation Failed" % new_directory) 
Directory debugpointer/python/posts Created Successfully 

The other option is to check if a directory already exists or not, that would also help in validating existence of the directory path before creating the directory.

As you see in the above code examples, it’s pretty simple to create folders recursively in Python.

And there you have it, a comprehensive understanding of creating directories recursively in Python. We’ve explored various methods and techniques to achieve this task, providing you with the flexibility to adapt to different scenarios. The ability to programmatically create directories in a recursive manner is a valuable skill that can simplify file organization and directory management in your Python projects. I hope this knowledge empowers you to become a more efficient and productive Python developer. Happy coding and creating directories recursively!

Источник

prabindh / dirlist_creator.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

import os
import json
def path_to_dict ( path ):
d =
if os . path . isdir ( path ):
d [ ‘type’ ] = «directory»
d [ ‘children’ ] = [ path_to_dict ( os . path . join ( path , x )) for x in os . listdir \
( path )]
else :
d [ ‘type’ ] = «file»
return d
print json . dumps ( path_to_dict ( ‘.’ ))
# Output like below
# From https://stackoverflow.com/questions/25226208/represent-directory-tree-as-json
«»»
«type»: «directory»,
«name»: «hello»,
«children»: [
«type»: «directory»,
«name»: «world»,
«children»: [
«type»: «file»,
«name»: «one.txt»
>,
«type»: «file»,
«name»: «two.txt»
>
]
>,
«type»: «file»,
«name»: «README»
>
]
>
«»»
#!python3 import os import json def path_to_dict(path): d = os.path.basename(path): <>> if os.path.isdir(path): d[os.path.basename(path)]['type'] = "directory" d[os.path.basename(path)]['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir(path)] else: d[os.path.basename(path)]['type'] = "file" return d with open('MANIFEST.JSON', 'w', encoding='utf-8') as f: json.dump(path_to_dict('.'), f, ensure_ascii=False, indent=4)

So I’ve modified it to this point. However, my goal is to represent the children as one single object with each child being a key of that single object. However, I don’t know an equivalent to the list comprehension here: [path_to_dict(os.path.join(path,x)) for x in os.listdir(path)]

It gives output like this:

< ".": < "type": "directory", "children": [ < "css": < "type": "directory", "children": [ < "index.css": < "type": "file" > > ] > >, < "desktop.ini": < "type": "file" > >, < "dir2json.py": < "type": "file" > >,

and so on.
However, with this current structure, to access the files in JavaScript, I’d have to do something like filesObj[«.»][«css»][«children»][0][«index.css»] which is not pretty. That index right there can really mess me up because it would have me to expect to know the name of the file behind an index. filesObj[«.»][«css»][«children»][«index.css»] would be better in this case but I’m really struggling how to make children a subobject.

EDIT:
I solved it but probably not the correct way. However, the end result was how I wanted it. Apologies if this is incorrect. I just converted the array of dicts into a single dict.

#!python3 import os import json def path_to_dict(path): d = os.path.basename(path): <>> if os.path.isdir(path): d[os.path.basename(path)]['type'] = "directory" d[os.path.basename(path)]['children'] = dict((key,d[key]) for d in [path_to_dict(os.path.join(path,x)) for x in os.listdir(path)] for key in d) else: d[os.path.basename(path)]['type'] = "file" return d with open('MANIFEST.JSON', 'w', encoding='utf-8') as f: json.dump(path_to_dict('.'), f, ensure_ascii=False, indent=4)
< ".": < "type": "directory", "children": < "css": < "type": "directory", "children": < "index.css": < "type": "file" > > >, "desktop.ini": < "type": "file" >, "dir2json.py": < "type": "file" >,

Источник

Читайте также:  Html image width responsive
Оцените статью