Ici, si le fichier spécifié (text.txt) n'existe pas, créez un fichier (text.txt), et s'il existe, écrivez "test" dans le fichier.
sample.py
import os
import pathlib
TEXT_FILE = "text.txt"
if not os.path.exists(TEXT_FILE):
    pathlib.Path(TEXT_FILE).touch()
    print("créé")
else:
    with open(TEXT_FILE, "w") as file:
        file.write("test")
        print("Écrit")
#Résultat de sortie (1ère fois)
#créé
#Résultat de sortie (deuxième fois)
#Écrit
C'était une combinaison d'os et de pathlib, et il était très facile de créer un fichier vide.
Recommended Posts