0
1

More than 3 years have passed since last update.

指定ファイルが存在しないとき新しいファイルを作成する方法—ファイルが存在していれば書き込む

Last updated at Posted at 2019-12-24

ここでは、もし指定のファイル(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の組み合わせででき、とても簡単に空のファイルを作成することができた。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1