python - 如何检查文件是否存在,如果不存在则创建并向其写入字符?
问题描述
我需要检查 Python 是否存在文件,如果不存在则创建它,然后在其中写入一个字符。
我试过了:
if os.path.exists(host_file) == False:
open(host_file, "w").close
但我还需要在其中写一个字符。
有没有办法在不重新打开文件的情况下做到这一点?
解决方案
使用with...as
关键字,它会自动关闭文件。
import os
if not os.path.exists(host_file):
with open(host_file, "w") as f:
f.write('ha')
推荐阅读
- python - 无法在 python 中找到文本的 xpath 元素
- javascript - React Native:如何将数据从屏幕传递到另一个?
- c++ - 无法在 Visual Studio 中打开文件
- java - 如果我们在 dockerfile 中使用 CMD,Docker 多阶段构建会失败
- spacy - spaCy 仅使用某些组件
- microsoft-teams - 如何让 OnPost 在 Microsoft Teams 中触发
- c++ - 关于标准容器内边界检查的问题
- tensorflow - 资源调用 close -flutter/tflite 错误失败
- android - Android更改搜索栏颜色
- django - Django csrf_protect 装饰器不起作用