0

I have the directory, where I have to store all the items separately in the list of folders. This list includes exactly the same folders only with incrementing number, as you can see below:

enter image description here

Because I am going to have more than 200 folders, I decided to create all of them by using Python console in QGIS.

My approach so far looks as you can see below:

 import os
 path='C:\\Users\\mk\\Desktop\\AX\\Pre survey\\Tyton'
 os.chdir(path)
 for i in range (1,208):
 Newfolder='Strand-' + str(i)
 os.makedirs(Newfolder)

As per the tutorial below:

https://www.youtube.com/watch?v=4nr0eW3w1u4&ab_channel=PyBTV

Since I managed to create one folder, there is a problem with the batch of these folders.

First of all, I cannot put something like "leading 0", as I tried:

    for i in range (001,208)

I cannot do this, but I need the folder numeration as shown in the image.

Another issue is, that if I use the whole code presented, Python throws an error:

IndentationError: expected an indented block

debugging the following line:

    Newfolder='Strand-' + str(i)

The examples how to solve this error are here:

https://stackoverflow.com/questions/4446366/why-am-i-getting-indentationerror-expected-an-indented-block

https://stackoverflow.com/questions/492387/indentationerror-unindent-does-not-match-any-outer-indentation-level

but i couldn't apply them to my situation.

How can I do the batch directory creation with Python, preferably by QGIS python console?

1 Answer 1

1

Try this:

import os
path='C:\\Users\\mk\\Desktop\\AX\\Pre survey\\Tyton\\'
os.chdir(path)
for i in range (1,208):
    newfolder=path + 'Strand-' + str(format(i, '03'))
    os.mkdir(newfolder)

About your errors:

3
  • Nothing happens. Maybe is something to add?
    – Geographos
    Commented Mar 31, 2021 at 10:19
  • OK I see that it works, but the path is slightly wrong, as the folders aren't created at the path: path='C:\\Users\\mk\\Desktop\\AX\\Pre survey\\Tyton\\' but here: path='C:\\Users\\mk\\Desktop\\AX\\Pre survey\\' it's simply one folder up. What is missing here then?
    – Geographos
    Commented Mar 31, 2021 at 10:28
  • 1
    Yes! I found an error! I forgot about \\ at the very end of my path. hence Python saved my folders in one level up and added the Tyton prefix. Thanks a lot!
    – Geographos
    Commented Mar 31, 2021 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.