Sunday, May 15, 2016

How to make Multiple Folders/Directories in Python

Hello,
Today, I want to discuss with you how you could create folders or directories on your PC.

You could easily create folders on your computer through the folder explorer at "New Folder".


However, it will be more efficient to use script if the folders to be created are plenty.

The OS python module is used to create and manipulate folder/directories in python. In general, this module provides a portable way of using operating system dependent functionality.

Lets take a look at THREE options or ways to create folders on our computer with python script.

Note: All the option we will discuss below assumes you are creating the folders at the same location as your script file.

Making directories or folders - OPTION 1

Lets assume that we want to create folders based on a given number of folders. The code below allows the script user to specify the number of folders he/she wants to create/make:-

import os

def main():
 dir_num = int(raw_input("Enter number of dirs to create: "))

 for dir in range(dir_num):
  dir_name = "Folder_%s" %dir # Creates the directory name
  os.mkdir(dir_name) #Creates directories in current directory
main()

If we run the code above and specify 20 as the number of directories to be created, boom! Twenty directories will be created.



Making directories or folders - OPTION 2

In this option, we have the names of the folders to be created in a list and the script creates folders based on the list content.

import os

folders = ['2001','2002','2003', '2004', '2005']

for folder in folders:
    os.mkdir(folder)



Making directories or folders - OPTION 3

Here, we want the user be able to specify the start number and end number of folders. This is useful when for example creating folders that span across some years. For instance to create folders from year 2000 to 2020.

import os

i = int(raw_input("Enter Start Number: "))
j = int(raw_input("Enter End Number: "))

while i <= j:
    os.mkdir(str(i))
    i += 1


That is it!
I hope you like the post? Be free to comment or ask question.

No comments:

Post a Comment