茨の道も一歩から

インフラ構築からプログラミング(Python・JavaScript)までITに関するブログです。

Python入門:ファイル操作

pathlib

from pathlib import Path

ファイル一覧取得

base_dir = Path('public/')
files = [file for file in base_dir.glob('*.csv')]

ファイルの読み書き

モード

モード 説明 既存ファイル無 既存ファイル有
'r' ファイルの読み込み エラー 読み込み
'w' ファイルの書き込み 新規ファイル作成 上書き
'x' ファイルの書き込み 新規ファイル作成 エラー
'a' ファイルの書き込み 新規ファイル作成 文末から追記
'b' バイナリモード
't' テキストモード

読み込みメソッド

メソッド 説明
read() 文字列として全行読み込む
readline() 1行を文字列として読み込む
readlines() 1行をリストの要素として全行読み込む

書き込みメソッド

メソッド 説明
write(str) 文字列(str)を書き込む

サンプルコード

with open('input.txt', 'r', encoding='utf-8') as f:
    df = f.readlines()
print(df)

with open('output.txt', 'w', encoding='utf-8') as f:
  f.write(df)

JSON

インポート

import json

alph = {'Alphabet': {'A': 'a', 'B': 'b'}}

JSON出力(文字列)

s = json.dumps(alph)
print(s, type(s))
# {"Alphabet": {"A": "a", "B": "b"}} <class 'str'>

JSON入力(文字列)

d = json.loads(s)
print(d, type(d))
# {'Alphabet': {'A': 'a', 'B': 'b'}} <class 'dict'>

JSON出力(ファイル)

with open('sample.json', 'w') as f:
    json.dump(alph, f)

JSON入力(ファイル)

with open('sample.json', 'r') as f:
    df = json.load(f)
print(df, type(df))
# {'Alphabet': {'A': 'a', 'B': 'b'}} <class 'dict'>

CSV

インポート

import csv

a = [['A', 'a'], ['B', 'b']]

CSV出力(ファイル)

with open('sample.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(a)

CSV入力(ファイル)

with open('sample.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
# ['A', 'a']
# ['B', 'b']