os.mkdir(path) returns OSError when directory does

2020-02-08 10:16发布

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.mkdir(path) raises an OSError that the path already exists.

For example, I call:

os.mkdir(test)

This call results in OSError: [Errno 17] File exists: 'test' even though I don't have a test directory or a file named test anywhere.

NOTE: the actual path name I use is not "test" but something more obscure that I'm sure is not named anywhere.

Help, please?

9条回答
一夜七次
2楼-- · 2020-02-08 10:27

You have a file there with the name test. You can't make a directory with that exact same name.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-02-08 10:30

Just check if the path exist. if not create it

if not os.path.exists(test):
        os.makedirs(test)
查看更多
Melony?
4楼-- · 2020-02-08 10:36

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.

查看更多
ゆ 、 Hurt°
5楼-- · 2020-02-08 10:36

I also faced the same problem, specially, when the string 'test' contains the multiple directory name. So when 'test' contains the single directory -

if not os.path.exists(test):
    try:
        os.makedir(test)
    except:
        raise OSError("Can't create destination directory (%s)!" % (test))  

If the 'test' contains multiple directory like '\dir1\dir2' then -

if not os.path.exists(test):
    try:
        os.makedirs(test)
    except:
        raise OSError("Can't create destination directory (%s)!" % (test))  
查看更多
放我归山
6楼-- · 2020-02-08 10:40

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)
查看更多
干净又极端
7楼-- · 2020-02-08 10:47

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.

查看更多
登录 后发表回答