Here, if the specified file (text.txt) does not exist, create a file (text.txt), and if it does exist, write "test" to the file.
sample.py
import os
import pathlib
TEXT_FILE = "text.txt"
if not os.path.exists(TEXT_FILE):
pathlib.Path(TEXT_FILE).touch()
print("created")
else:
with open(TEXT_FILE, "w") as file:
file.write("test")
print("Written")
#Output result (1st time)
#created
#Output result (second time)
#Written
It was a combination of os and pathlib, and it was very easy to create an empty file.
Recommended Posts