[PYTHON] How to create a new file when the specified file does not exist — write if the file exists

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

How to create a new file when the specified file does not exist — write if the file exists
How to create a config file
When incrementing the value of a key that does not exist
[Learning memo] Create if the directory does not exist / Get the files in the directory
How to create a JSON file in Python
Read the Python-Markdown source: How to create a parser
How to create a submenu with the [Blender] plugin
How to deal with Django's Template Does Not Exist
What to do if sys / cdefs.h does not exist
Create a python script to check if the link at the specified URL is valid
How to check if a value exists in an enum
Check when the Docker container does not connect to the Internet
[Beginner] What to do when "[Errno 2] File b'test.csv' does not exist: b'test.csv" is displayed when reading pandas csv
A decorator that notifies you via AWS-SNS if the function does not finish within the specified time
Create a shell script to run the python file multiple times
How to make a command to read the configuration file with pyramid
How to output the output result of the Linux man command to a file
How to create a CSV dummy file containing Japanese using Faker
How to write a docstring to create a named tuple document with sphinx
How to write a Python class
How to create a Conda package
Write standard output to a file
How to create a virtual bridge
How to create a Dockerfile (basic)
A story about what to do when a bad interpreter: Not such file or directory appears in Anaconda3 and how to investigate the cause.
Think about how to write a filter with the Shotgun API-Contact Versions
How to fix a bug that jupyter notebook does not start automatically
How to specify a .ui file in the dialog / widget GUI in PySide
Test & Debug Tips: Create a file of the specified size in Python
How to put a line number at the beginning of a CSV file
How to create a wrapper that preserves the signature of the function to wrap
How to write a string when there are multiple lines in python
[Introduction to Python] How to write a character string with the format function
[Development environment] How to create a data set close to the production DB
How to create a git clone folder
I created a script to check if English is entered in the specified position of the JSON file in Python.
Golang mysql CREATE DATABASE IF NOT EXISTS
How to create a repository from media
Script to create a Mac dictionary file
Install the python library when you're not a sudoer (or if you don't want new users to be Sudoer, but you don't mind having the Python Library installed as you like)
Example of what to do when the sample script does not work (OpenCV-Python)
A story that sometimes does not work if pip is up to date
A decorator that does something if the function doesn't finish within the specified time
Zip-compress any file with the [shell] command to create a file and delete the original file.
Solution to the problem that build does not end when installing OpenCV (PEP517)
Send a direct love email to a new user when a new user joins the Slack team
[AWS] Wordpress How to deal with "The response is not a correct JSON response"
What to do when the graph does not appear in jupyter (ipython) notebook
How to make a Raspberry Pi that speaks the tweets of the specified user
What to do if you get the error "Error: opencv3: Does not support building both Python 2 and 3 wrappers" when installing openCV 3
How to calculate the volatility of a brand
How to read a CSV file with Python 2/3
How to disguise a ZIP file as a PNG file
How to create a Python virtual environment (venv)
How to create a function object from a string
If you want to create a Word Cloud.
Why does Python have to write a colon?
How to write a ShellScript Bash for statement
How to remember when you forget a word
Try to create a new command on linux
How to create a shortcut command for LINUX