pythonlistoperating-systemrange

mkdir: path should be string not generator


This is my code-

import os
os.mkdir(str(i) for i in list(range(1,11)))

It gives the error in title. What is wrong?


Solution

  • mkdir takes as an argument a string. You are passing it a generator expression that will generate successive values '1', '2', ... '10' when you iterate it. You need to use a loop to make individual calls passing a single string argument:

    import os
    
    for i in range(1, 11):
        os.mkdir(str(i))
    

    By the way, the expression list(range(1, 11)) will create a list from a range object. But if you are going to be using the result in a for loop as in the above code, it is wasteful to create the list; just use the range object directly.

    You could (but shouldn't) use a list comprehension in the following way:

    import os
    
    [os.mkdir(str(i)) for i in range(1, 11)]
    

    Each element of the created list is just the return value from calling os.mkdir. Do you see the difference between this and your original code? But this is considered to be very poor, non-Pythonic code since you would be creating a list solely for its side effects. So don't do it! :-)