様々なファイル操作 ライブラリメモ (python3.4)

CSVファイル

# csvファイルの出力 リストとして出力
with open("sample.csv",mode='r',encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# csv -> tsv
with open("sample.csv",mode='r',encoding='utf-8') as read_file:
    reader = csv.reader(read_file)
    with open("sample.tsv", mode='w', encoding='utf-8') as write_file:
        writer = csv.writer(write_file, delimiter='\t')
        for row in reader:
            writer.writerow([row[0],row[1],row[2]])

# 辞書として出力
with open('sample.csv',mode='r',encoding='utf-8') as f:
    for row in csv.DictReader(f):
        print(row)

INIファイル

# iniファイルの読み込み
from configparser import ConfigParser
config = ConfigParser()
print("")
print(config.read('config.ini'))
print(config.sections())
print(config.options("USER_A"))
print("USER_B" in config)
print(config.get("USER_A",'group'))
print(config.get('USER_A','limit'))

YAMLファイル

# yamlファイルの読み込み
import yaml
file = open('sample.yml','r')
conf = yaml.load(file)
print(conf)
print(conf["database"]["port"])

# yamlファイルの書き込み
hosts = {'web_server': ['192.168.0.2', '192.168.0.3'] , 'db_server': ['192.168.0.7']}
with open("dump.yml","w") as f:
    f.write(yaml.dump(hosts,default_flow_style=False))

jsonファイル

# jsonエンコード
import json
data = [{'id':123, 'entries':{'url': 'python.org','hashtags':['#python','#pythonjp']}}]
print(json.dumps(data,indent=2))

# jsonデコード
json_str = '["ham",1.0,{"a":false,"b":null}]'
print(json.loads(json_str))

Excelファイル

# Excelファイル
# 読み込み
import openpyxl
wb = openpyxl.load_workbook("sample.xlsx")
print(wb.get_sheet_names())
ws = wb.get_sheet_by_name("Sheet1")
print(ws.get_highest_column())
print(ws.get_highest_row())
print(ws["A4"].value)
a2 = ws.cell("A2")
print(a2.value)

# セルの値を順に取得
wb = openpyxl.load_workbook('sample.xlsx', data_only=True)
ws = wb.get_active_sheet()

print('A1 -> A2 ... B1 -> B2 の順で取得')
for row in ws.rows:
    for cell in row:
        print(cell.value)
print("")
for column in ws.columns:
    for cell in column:
        print(cell.value)

# Excel 書き込み
wb = openpyxl.Workbook()
ws = wb.create_sheet(index=0,title="New Sheet")
ws["A1"] = 100

wb.save(filename="new_book.xlsx")

参考文献

Python ライブラリ厳選レシピ

Python ライブラリ厳選レシピ