0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【覚書】pythonコピペ関数(001)

Last updated at Posted at 2025-01-11

個人用覚書

個人的に使用頻度が高い割に忘れがちなコードをまとめておきます。

標準モジュール

日付→文字列

sample.py
from datetime import datetime

def get_current_date_time_string():
    current_date = datetime.now()
    return current_date.strftime("%Y年%m月%d日%H時%M分")

# 関数の使用例
print(get_current_date_time_string())

ファイルI/O

jsonファイル

読み込み

sample.py
import json

def load_json_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
        return data
    except FileNotFoundError:
        print(f"エラー: ファイル '{file_path}' が見つかりません。")
        return None
    except json.JSONDecodeError:
        print(f"エラー: ファイル '{file_path}' の JSON 形式が無効です。")
        return None
    except Exception as e:
        print(f"エラー: ファイルの読み込み中に問題が発生しました: {str(e)}")
        return None

# 関数の使用例
file_path = 'path/to/your/file.json'
json_data = load_json_file(file_path)

if json_data is not None:
    print(json_data)

書き込み

sample.py
import json

def write_json_file(file_path, data):
    try:
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False, indent=2)
        print(f"JSONデータが '{file_path}' に正常に書き込まれました。")
    except IOError:
        print(f"エラー: ファイル '{file_path}' に書き込めません。")
    except TypeError:
        print(f"エラー: 指定されたデータはJSON形式に変換できません。")
    except Exception as e:
        print(f"エラー: ファイルの書き込み中に問題が発生しました: {str(e)}")

# 関数の使用例
data = {
    "名前": "山田太郎",
    "年齢": 30,
    "趣味": ["読書", "旅行", "プログラミング"]
}

file_path = 'path/to/your/output.json'
write_json_file(file_path, data)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?