ここでは、もし指定のファイル(text.txt)が存在していなければ、ファイル(text.txt)を作成し、存在していればファイルに"test"と書き込むことをやってみる。
sample.py
import os
import pathlib
TEXT_FILE = "text.txt"
if not os.path.exists(TEXT_FILE):
pathlib.Path(TEXT_FILE).touch()
print("作成しました")
else:
with open(TEXT_FILE, "w") as file:
file.write("test")
print("書き込みました")
# 出力結果(1回目)
# 作成しました
# 出力結果(2回目)
# 書き込みました
osとpathlibの組み合わせででき、とても簡単に空のファイルを作成することができた。