# ファイル --------------------------------------------------------
# 新規作成(上書き)
f = open("t.txt", "w")
f.write("test")
f.close()
# 追加の場合
f = open("t.txt", "a")
f.write("test")
f.close()
# print()での書き込み
f = open("t.txt", "w")
print("test", file=f)
f.close()
# with
# close()しなくても自動で閉じる
with open ("t.txt", "w") as f:
f.write("test")
# 読み込み方法
s = """\
abc
def
ghi
"""
with open("t.txt", "w") as f:
f.write(s)
# 1度に読み込む
with open("t.txt", "r") as f:
print(f.read())
# 1行ごと読み込む
with open("t.txt", "r") as f:
while True:
line = f.readline()
print(line, end="")
if not line:
break
# 指定文字数ごと読み込む
with open("t.txt", "r") as f:
chunk = 2
while True:
line = f.read(chunk)
print(line)
if not line:
break
# seekでの読み込み
# tell() 現在のカーソルの位置を取得
# seek() 指定した位置にカーソルを移動
with open("t.txt", "r") as f:
print(f.tell()) # 0
f.seek(1)
print(f.read(2)) # bc
print(f.tell()) # 3
# 書き込み・読み込みモード
# w+の場合、開いた時点でファイルが空になる
# r+の場合、最初にファイルが存在している必要がある
s = """\
abc
def
ghi
"""
with open("t.txt", "w+") as f:
f.write(s)
f.seek(0)
print(f.read())
# テンプレート --------------------------------------------------------
import string
s = """\
123
$a
"""
t = string.Template(s)
print(t.substitute(a = "234"))
# CSV --------------------------------------------------------
import csv
# 書き込み
with open("t.csv", "w", newline="") as c:
fields = ["name","age"]
writer = csv.DictWriter(c, fieldnames=fields)
writer.writeheader()
writer.writerow({"name":"taro","age":20})
writer.writerow({"name":"jiro","age":21})
#読み込み
with open("t.csv", "r") as c:
reader = csv.DictReader(c)
for r in reader:
print(r["name"], r["age"])
# ファイル操作 --------------------------------------------------------
import os
import pathlib
import glob
import shutil
# 昔のファイル作成方法
with open ("t.txt", "w") as f:
f.write("test")
# ファイル削除
os.remove("t.txt")
# 現在のファイル作成方法
pathlib.Path("t.txt").touch()
# 存在確認
print(os.path.exists("t.txt")) # True
# ファイルかどうか
print(os.path.isfile("t.txt")) # True
# ディレクトリかどうか
print(os.path.isdir("t.txt")) # False
# リネーム
os.rename("t.txt", "t2.txt")
# コピー
shutil.copy("t2.txt", "t3.txt")
os.remove("t2.txt")
os.remove("t3.txt")
# シムリンク
# os.symlink()
# ディレクトリ作成
os.mkdir("test")
# ディレクトリ削除(空)
os.rmdir("test")
# ディレクトリ・ファイルの一覧
os.mkdir("test")
os.mkdir("test/test1")
pathlib.Path("test/test1/a.txt").touch()
# ディレクトリ
print(os.listdir("test")) # test1
# ファイル
print(glob.glob("test/test1/*")) # test/test1/a.txt
# ディレクトリ削除(空以外)
shutil.rmtree("test")
# カレントパス取得
print(os.getcwd())
# zip --------------------------------------------------------
import zipfile
if not os.path.exists("z1"):
os.mkdir("z1")
with open ("z1/t1.txt", "w") as f:
pass
with open ("z1/t2.txt", "w") as f:
pass
# 圧縮
with zipfile.ZipFile("test.zip", "w") as z:
# z.write("z/t1.txt")
# z.write("z/t2.txt")
# 複数の場合、以下のようにも書ける
for i in glob.glob("z1/**", recursive=True):
z.write(i)
# 解凍
with zipfile.ZipFile("test.zip", "r") as z:
z.extractall("z2")
# temp --------------------------------------------------------
import tempfile
# バッファをテンプとする場合
with tempfile.TemporaryFile(mode="w+") as t:
t.write("1")
t.seek(0)
print(t.read()) # 1
# 実際のファイルをテンプとする場合
# プログラム終了時に削除される
with tempfile.NamedTemporaryFile(delete=False) as t:
print(t.name) # テンプファイルのパス
with open(t.name, "w+") as f:
f.write("2")
f.seek(0)
print(f.read()) # 2
# ディレクトリを作成する
# プログラム終了時に削除される
with tempfile.TemporaryDirectory() as t:
print(t)
# プログラムの起動 --------------------------------------------------------
import subprocess
subprocess.run("dir", shell=True)
# 日付 --------------------------------------------------------
import datetime
# 現在
now = datetime.datetime.now()
print(now)
print(now.isoformat())
print(now.strftime("%Y/%m/%d/-%H:%M:%S"))
# 年月日
today = datetime.date.today()
print(today)
print(today.isoformat())
print(today.strftime("%Y/%m/%d"))
# 時分秒
t = datetime.time(hour=1, minute=5, second=10)
print(t) # 01:05:10
# 計算
# timedelta()
now = datetime.datetime.now()
d = datetime.timedelta(weeks=-1) # 1週間前
# weeks, days, hours, minutes, second, microseconds
print(now + d)