Python ファイル書込み|追記

Pythonでファイルの書込みや追記などの処理を行いたい場合openTextIOWrapperを取得し書込み処理を行います

file_path_name = 'text_write.txt'
moji = """1行目:書きたい文字列
2行目:書きたい文字列
"""
with open(file_path_name, mode='w') as f:
    f.write(moji)

openのmode=’w’で書込みですが、ファイルが無い場合エラーになります。

従って書き込みたいファイルが存在しない場合mode=’x’を使います

file_path_name = 'text_write.txt'
moji = '1行目:書きたい文字列'
#ファイルを作って書き込む
with open(file_path_name, mode='x') as f: 
    f.write(moji)

ファイルが存在する場合、mode=’x’ではFileExistsErrorになります。

その場合、os.path.exists()などでファイルの存在を確認し‘x’/’w’を判断する。

import os
file_path_name = 'text_write.txt'
moji = '1行目:書きたい文字列'
#ファイルがあれば「ファイル書込み」それ以外は、「ファイル新規作成書込み」
write_mode = 'w' if os.path.exists(file_path_name) else 'x'
with open(file_path_name, mode=write_mode) as f: 
    f.write(moji)

ファイルに追記したい場合、mode=’a’を使います

import os
file_path_name = 'text_write.txt'
moji = '1行目:書きたい文字列'
#ファイルがあれば「ファイル追記」それ以外は、「ファイル新規作成書込み」
write_mode = 'a' if os.path.exists(file_path_name) else 'x'
with open(file_path_name, mode=write_mode) as f: 
    f.write(moji)

Python ファイルの存在を確認するFileExists

Python スクリプトで、ローカルにあり指定したファイルやフォルダが存在するのかを確認する方法

共通のパス名操作(os.path)標準機能を使います

import os
file_path = "./a.txt" #このファイルがあるかどうか
file_exists = os.path.exists(file_path)
if file_exists:
    print("ファイルあり")
    

ファイルだけを確認したい場合

import os
file_path = "./a.txt" #このファイルがあるかどうか
file_exists = os.path.isfile(file_path)
if file_exists:
    print("ファイルあり")

ディレクトリを確認したい場合

import os
dir_path = "utils"
dir_exists = os.path.isdir(dir_path) #ディレクトリの有無を確認
if dir_exists:
    print("ディレクトリあり")

2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED