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("ディレクトリあり")

Python DictからJSON文字列変換 dumps()

Python json.dumps()

PythonDictからJSON文字列に変換するにはjson.dumps()を使います。下記は簡単なコード例です。

dic1 = {"NAME": "Robert"}
dic1["ARRAY"] = [1,2,"A"]
dic1["AGE"] = 50
str1 = json.dumps(dic1)
print(str1)

上のコードは変数(dic1)に入れたデータをJSON文字列に変換しています。

printされた結果は「{“NAME”: “Robert”, “ARRAY”: [1, 2, “A”], “AGE”: 50}」このようにJSON文字列で出力されました。

また、このJSON文字列に 改行やインテントをキレイにつけて出力したい場合は下記のように記述します。

str1 = json.dumps(dic1, indent=2, separators=(',', ':'))
print(str1)

結果は、下記のようにインテントと改行が付きます

{
  "NAME":"Robert",
  "ARRAY":[
    1,
    2,
    "A"
  ],
  "AGE":50
}

Dictの中に、Decimalの値が入っている場合json.dumps()を実行すると 「Object of type Decimal is not JSON serializable」とエラーが出ます。その場合は、default引数を使ってDecimalの場合の処理を記述できます。

下記のコードはdictの変数にDecimalが入っている場合の対処コード例です。

dic1 = {"NAME": "Robert"}
dic1["RATE"] = decimal.Decimal(1.5)
str1 = json.dumps(dic1, indent=2, separators=(',', ':'), default=lambda _ : float(_) if isinstance(_, decimal.Decimal) else TypeError)
print(str1)

実行結果は下記です。

{
  "NAME":"Robert",
  "RATE":1.5
}