6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python ファイル処理

6
Posted at

ファイルを開く

open()関数
open(ファイル名[, モード[, エンコード[, エラー処理]]])

ファイルを閉じる

close()関数
F.close

ファイルを読み込む

read()関数
F.read([整数のサイズ])
整数のサイズがオプションとして指定されていると、サイズ分だけ読み込みを行います。

readline()関数
F.readline([整数のサイズ])
ファイルから1行を読み込み、文字列として返します。

readlines()関数
F.readlines([整数のサイズ])
ファイルから複数行を読み込みます。

ファイルから1行ずつ読み込んで処理をする

f = open("test.txt", 'r', encoding='utf-8')
for line in f:
    print(line, end= " ")

他にreadlines()メソッドを使う方法もありますが、大きなファイルを扱う場合などに問題が発生することがあります。特別な理由がない限り、ファイルオブジェクトをそのままfor文に添えたほうがよいでしょう。

ファイルに書き出す

write()関数
F.write(文字列)
モードを指定してファイルを開き、書き出す

f = open("newfile.txt", "w", encodint="UTF-8") ← ファイルをモードwで開く
f.write(s) ← 変数sの文字列をファイルに書き出す
f.close ← ファイルを閉じる
6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?