Python 覚え書き
Python に関する自分用の覚え書きメモです。
関数関連¶
main 関数¶
1 2 3 4 5 6 |
|
リスト関連¶
比較¶
リストの比較は ==
で行えます。
list1 = ["a", "b", "c"]
list2 = ["a", "c", "b"]
print(list1 == list2)
# False
list1 = sorted(["a", "b", "c"])
list2 = sorted(["a", "c", "b"])
print(list1 == list2)
# True
ファイル関連¶
読み込み¶
ファイルを一行ずつ読み込み、リストで返す¶
with open(path) as f:
lines = [s.rstrip() for s in f.readlines()]
ファイルを一行ずつ読み込み、改行して str で返す¶
改行を削除する為、リスト内包表記で rstrip()
します。
with open(path) as f:
lines = "\n".join([s.rstrip() for s in f.readlines()])
書き込み¶
リストの内容を改行しながらファイルへ書き込む¶
改行する為に "\n".join()
します。
with open(path, "w") as f:
f.write("\n".join(lines))