0

I'm python beginner. I wanted to make 50 directories in my laptop with python. IDK what to do plz help

import os
from os.path import *

home = expanduser('~')

dl_path = home + '\\Downloads'

def main():
    if not os.path.exist(dl_path):
        print("path does'nt exist")
        os.makedirs(dl_path)

if __name__ == '__main__':
    a = 1
    while a<= 50:
        main()
        a += 1

This is my code which doesn't work :( I don't know if it's given an error but here it is: enter image description here

Yangelixx
  • 53
  • 9

1 Answers1

2

Instead of '+' it is better to use os.path.join - it works with filenames in a smarter way. Also, you have forgotten to elaborate on the else statement, when you do the actual job instead of throwing an exception. Also, you need a new name for each new directory - they can't all have the same name. Also, do you want nested directories or directories at the same level?

This makes directories at the same level.

import os
from os.path import *

home = expanduser('~')

dl_path = os.path.join(home, 'Downloads')

def main():
    if not os.path.exist(dl_path):
        print("path does'nt exist")
    else:
        a = 1
        while a <= 50:
            os.makedirs(os.path.join(dl_path, str(a)))
            a += 1

if __name__ == '__main__':
    main()

This makes nested directories:

import os
from os.path import *

home = expanduser('~')

dl_path = home

def main():
    if not os.path.exist(dl_path):
        print("path does'nt exist")
    else:
        a = 1
        while a <= 50:
            dl_path = os.makedirs(os.path.join(dl_path, 'Downloads'))
            a += 1
        os.makedirs(dl_path)

if __name__ == '__main__':
    main()
freude
  • 3,632
  • 3
  • 32
  • 51
  • 1
    I would suggest to use for loop for known number of iterations: https://support.khanacademy.org/hc/en-us/articles/203327020-When-do-I-use-a-for-loop-and-when-do-I-use-a-while-loop-in-the-JavaScript-challenges- – johnymachine May 02 '21 at 09:27
  • yes, agree, it is better in this case. – freude May 02 '21 at 11:09