0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

テキストファイル読み込みのすゝめ

Last updated at Posted at 2023-03-24

はじめに

Pythonでtextファイルの読み書きする際、大雑把に3種類の方法を使うことができる。

  1. すべてをstrとして扱う
  2. すべてをlistとして扱う
  3. 一行ずつ扱う

このようなtextファイルを準備したとする。

input.txt
aaaaa
bbbbb
ccccc
ddddd
eeeee

すべてをstrとして扱う

一番直感的なやり方?
ファイルの全内容をstrとして一つの変数に格納する。

# ファイルを読み込む
inputfile = "input.txt"
with open(inputfile, mode="r", encoding="utf8") as f:
    data = f.read()

# 処理する
print(data)

# 出力する
outputfile = "output.txt"
with open(outputfile, mode="w", encoding="utf8") as f:
    f.write(data)

dataは一つのstrとして扱われる。

aaaaa
bbbbb
ccccc
ddddd
eeeee

すべてをlistとして扱う

同じ形式のデータ形式が複数セクション分縦に積まれているような形式のtextファイルを読む際、セクションごとに分割して読みたいニーズがあるため、個人的には一番よく使っている。
f.readf.readlinesになり、f.writef.writelinesになっただけである。

# ファイルを読み込む
inputfile = "input.txt"
with open(inputfile, mode="r", encoding="utf8") as f:
    data = f.readlines()

# 処理する
print(data)

# 出力する
outputfile = "output.txt"
with open(outputfile, mode="w", encoding="utf8") as f:
    f.writelines(data)

dataは行ごとのstrを要素として持つlistとして扱われ、改行も含んだ状態で読み込まれる。

['aaaaa\n', 'bbbbb\n', 'ccccc\n', 'ddddd\n', 'eeeee']

一行ずつ扱う

でかいファイルを扱い、ヘッダー情報をキャッチしたら終わるなどという使い方をたまにする。for文で回し一行図ずつ取得する。

# ファイルを読み込む
inputfile = "input.txt"
with open(inputfile, mode="r", encoding="utf8") as f:
    for line in f:
        # 読むたびに行が進む
        print(line)

行ごとにprintさせている。

aaaaa

bbbbb

ccccc

ddddd

eeeee
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?