> For the complete documentation index, see [llms.txt](https://l1nwatch.gitbook.io/interview_exercise/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://l1nwatch.gitbook.io/interview_exercise/stackoverflow-about-python/jian-cha-wen-jian-jia-shi-fou-cun-zai-de-cao-zuo.md).

# 检查文件夹是否存在的操作

方法一：

```python
filename = "/my/directory/filename.txt"
dir = os.path.dirname(filename)

try:
    os.stat(dir)
except:
    os.mkdir(dir)

f = file(filename)
```

方法二：

```python
def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)
```

【注意】，如果在调用 `os.path.exists` 和 `os.makedirs` 之间被创建了，将会出现一个 `OSError`。然而捕获 `OSError` 并不能很好地解决这个问题，因为它将会忽略磁盘空间不足，没有足够权限等一些其他造成文件创建失败的因素

一个做法是捕获 OSError 异常并检查返回的错误代码

方法三：

```python
os.makedirs(self.path_dir, exist_ok=True)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://l1nwatch.gitbook.io/interview_exercise/stackoverflow-about-python/jian-cha-wen-jian-jia-shi-fou-cun-zai-de-cao-zuo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
