S-JIS[2018-01-20/2021-04-07] 変更履歴
Python3.6.4のファイル読み書きのメモ。
|
Pythonはopen関数でファイルを開く。(C言語のfopen相当)
open関数はfileオブジェクトを返す。
ファイルを開くモードをr, rb, w, wbといった文字で指定する。(この辺り、C言語のfopen関数とそっくり(笑))
テキストファイルを1行ずつ読み込む例。
パスを文字列で扱う | Pathオブジェクトを使用 |
---|---|
from pathlib import Path |
|
rpath = "example.txt" |
rpath = Path("example.txt") |
with open(rpath) as rfile: for line in rfile: print(line.rstrip()) |
with rpath.open() as rfile: for line in rfile: print(line.rstrip()) |
open関数のmode引数(第2引数)あるいはopenメソッドのmode引数(第1引数)を省略すると、テキストファイルの読み込みになる。[/2021-04-07]
(もしくは"r"
を指定する)
読み込んだ1行分のデータの末尾には改行コードも入っているので、不要であればstrip(rstrip)メソッドで削除する。
エンコーディングを指定する例。[2021-04-06]
with open("example.txt", encoding="UTF-8") as rfile:
with Path("example.txt").open(encoding="UTF-8") as rfile:
各行をまとめて読み込んでリストにする例。
with open("example.txt") as rfile: lines = rfile.readlines() # 末尾の改行を削除 lines = list(map(str.rstrip, lines)) print(lines)
ファイル全体をひとつの文字列として読み込む例。
パスを文字列で扱う | Pathオブジェクトを使用 |
---|---|
from pathlib import Path |
|
rpath = "example.txt" |
rpath = Path("example.txt") |
with open(rpath, encoding="UTF-8") as rfile: s = rfile.read() # 改行文字で分割 for line in s.split("\n"): if line != "": print(line) |
s = rpath.read_text("UTF-8") # 改行文字で分割 for line in s.split("\n"): if line != "": print(line) |
ちなみに、改行コード毎にsplitメソッドで分割すると、一番最後のデータの末尾も分割され、空行が出来てしまう。
改行コードで分割するならsplitlinesメソッドの方が便利。
# 改行文字で分割 for line in s.splitlines(): print(line)
テキストファイルを出力する例。
パスを文字列で扱う | Pathオブジェクトを使用 |
---|---|
from pathlib import Path |
|
wpath = "write.txt" |
wpath = Path("write.txt") |
with open(wpath, "w") as wfile: wfile.write("abc\n") wfile.write("def\n") |
with wpath.open("w") as wfile: wfile.write("abc\n") wfile.write("def\n") |
open関数のmode引数(第2引数)あるいはopenメソッドのmode引数(第1引数)に"w"を指定すると、テキストファイルの書き込みになる。[/2021-04-07]
エンコーディングを指定する例。[2021-04-06]
with open("write.txt", "w", encoding="UTF-8") as wfile:
with Path("write.txt").open("w", encoding="UTF-8") as wfile:
文字列のリストをファイルに出力する例。
lines = ["abc\n", "def\n", "ghi\n"] with open("write.txt", "w") as wfile: wfile.writelines(lines)
読み込んだファイルを書き込む例。[2021-04-06]
with open(rpath) as rfile, open(wpath, "w") as wfile: for line in rfile: wfile.write(line) |
with文で、複数のファイルを開くことが出来る。 |
with open(rpath) as rfile, open(wpath, "w") as wfile: for line in rfile: wfile.write(line) |
with文で複数のファイルを開く場合、カンマの直後で改行して複数行にすることは出来ない。 |
with open(rpath) as rfile, \ open(wpath, "w") as wfile: for line in rfile: wfile.write(line) |
with文で複数のファイルを複数行で指定したい場合、行継続文字「\」を使う。 |