首页 > 解决方案 > 如何检查文件是否存在,如果不存在则创建并向其写入字符?

问题描述

我需要检查 Python 是否存在文件,如果不存在则创建它,然后在其中写入一个字符。

我试过了:

if os.path.exists(host_file) == False:
    open(host_file, "w").close

但我还需要在其中写一个字符。

有没有办法在不重新打开文件的情况下做到这一点?

标签: python

解决方案


使用with...as关键字,它会自动关闭文件。

import os
if not os.path.exists(host_file):
    with open(host_file, "w") as f:
        f.write('ha')

推荐阅读