os.mkdir(path) returns OSError when directory does not exist

后端 未结 10 2173
挽巷
挽巷 2020-12-08 09:54

I am calling os.mkdir to create a folder with a certain set of generated data. However, even though the path I specified has not been created, the os.mkdi

相关标签:
10条回答
  • 2020-12-08 10:17

    Greg's answer is correct but doesn't go far enough. OSError has sub-error conditions, and you don't want to suppress them all every time. It's prudent to trap just expected OS errors.

    Do additional checking before you decide to suppress the exception, like this:

    import errno
    import os
    
    try:
        os.mkdir(dirname)
    except OSError as exc:
        if exc.errno != errno.EEXIST:
            raise
        pass
    

    You probably don't want to suppress errno.EACCES (Permission denied), errno.ENOSPC (No space left on device), errno.EROFS (Read-only file system) etc. Or maybe you do want to -- but that needs to be a conscious decision based on the specific logic of what you're building.

    Greg's code suppresses all OS errors; that's unsafe just like except Exception is unsafe.

    0 讨论(0)
  • 2020-12-08 10:17

    In Python 3.2 and above, you can use:

    os.makedirs(path, exist_ok=True)

    to avoid getting an exception if the directory already exists. This will still raise an exception if path exists and is not a directory.

    0 讨论(0)
  • 2020-12-08 10:18

    Simple answer that does not require any additional import, does not suppress errors such as "permission denied", "no space left on device" etc., yet accepts that the directory may already exist:

    import os
    
    try:
        os.mkdir(dirname)
    except FileExistsError :
        pass
    except :
        raise
    
    0 讨论(0)
  • 2020-12-08 10:19

    Maybe there's a hidden folder named test in that directory. Manually check if it exists.

    ls -a

    Create the file only if it doesn't exist.

    if not os.path.exists(test):
        os.makedirs(test)
    
    0 讨论(0)
  • 2020-12-08 10:23

    I don't know the specifics of your file system. But if you really want to get around this maybe use a try/except clause?

    try:
        os.mkdir(test)
    except OSError:
        print "test already exists"
    

    You can always do some kind of debugging in the meanwhile.

    0 讨论(0)
  • 2020-12-08 10:29

    Happened to me on Windows, maybe this is the case:

    Like you I was trying to :

    os.mkdir(dirname)
    

    and got OSError: [Errno 17] File exists: '<dirname>'. When I ran:

    os.path.exists(dirname)
    

    I got false, and it drove me mad for a while :)

    The problem was: In a certain window I was at the specific directory. Even though it did not exists at that time (I removed it from linux). The solution was to close that window \ navigate to somewhere else. Shameful, I know ...

    0 讨论(0)
提交回复
热议问题