0

I'm trying to create multiple folders in my current directory so I'm using os.mkdir() to do that. The problem is that this function returns an error if the folder already exists so I created a try/except block.

I would like it to skip the line if it encounters an error. The problem is that this would require one block per directory as I want it to check every single one of them individually.

I do realize that there probably exists another function that doesn't return an error, but I just want to know if it's possible to tell the computer to keep reading the block and simply skip any line that gives it an error, but not any other line.

So if I want to create dir1 to dir5, but dir3 already exists, having something like:

try:
    os.mkdir('dir1')
    os.mkdir('dir2')
    os.mkdir('dir3')
    os.mkdir('dir4')
    os.mkdir('dir5')
except:
    pass

I would like it to still create directory 1 through 5 instead of only creating 1 and 2. How can I achieve this?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
BloodLord
  • 49
  • 5

2 Answers2

3

Sure, but not the way you specify. You have to enter and leave the try block each time. Perhaps this:

for f in ['dir1', 'dir2', 'dir3', 'dir4', 'dir5']:
    try:
        os.mkdir(f)
    except:
        pass

It's generally a bad idea to have a silent, global failure such as the above. Instead, set your except block for a specific exception, and print a message to cover the event.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Prune
  • 76,765
  • 14
  • 60
  • 81
0

You can check if the folder actually exists before trying mkdir

for folder in ['dir1', 'dir2', 'dir3', 'dir4', 'dir5']:
    if not os.path.isdir(folder):
        os.mkdir(folder)
not_speshal
  • 22,093
  • 2
  • 15
  • 30