スポンサーリンク

【Python】open関数を使った外部ファイル操作

Python
スポンサーリンク

pythonで外部ファイルを読み込んで出力する方法。

ファイル読み込み “r”

外部テキストファイル(textfile.txt)を用意

Tokyo- Japan
New York- USA
Bangkok- Thailand
London- UK

テキストファイルを読み込んで表示

open関数でファイルをオープン。処理後には、ファイルをクローズする。

# オープン
text_file = open("textfile.txt", "r")

# ファイル全体を読み込む
print(text_file.read())

# クローズ
text_file.close()

結果

 Tokyo- Japan
New York- USA
Bangkok- Thailand
London- UK

一行読み込み

一行のみ読み込み

text_file = open("textfile.txt", "r")

# 一行読み込む
print(text_file.readline())

text_file.close()

結果

Tokyo- Japan

続けて実行すると次の行を読み込む

text_file = open("textfile.txt", "r")

# 一行読み込む
print(text_file.readline())

print(text_file.readline())

text_file.close()

結果

 Tokyo- Japan
New York- USA

すべての行を読み込み

readlinesとするとすべての行を読み込む。

 
text_file = open("textfile.txt", "r")

# すべての行を読み込む
print(text_file.readlines())

text_file.close()

結果

['Tokyo- Japan\n', 'New York- USA\n', 'Bangkok- Thailand\n', 'London- UK ']

行を指定して読み込み

text_file = open("textfile.txt", "r")

# インデックス2の行を読み込む
print(text_file.readlines()[2])

text_file.close()

結果

Bangkok- Thailand

ループで一行ずつ表示

各行を読み込んで、ループで一行ずつ出力

text_file = open("textfile.txt", "r")

for row in text_file.readlines():
print(row)

text_file.close()

結果

 Tokyo- Japan
New York- USA
Bangkok- Thailand
London- UK

ファイルに追記 “a”

ファイルに書き加えるには、以下のように第二引数を”a”とする。

append(追加する)の a で、ファイルの末尾に追加される。

text_file = open("text.txt", "a") 

末尾に1行追加

外部テキストファイル(text.txt)

Tokyo - Japan
New York - USA
Bangkok - Thailand
London - UK

ここに一行追加する。実行すると、外部ファイルが更新される。

text_file = open("text.txt", "a")

text_file.write("\nPeru - Lima")

text_file.close()

結果(text.txt)

Tokyo - Japan
New York - USA
Bangkok - Thailand
London - UK
Peru - Lima

\n は改行。繰り返し実行すると、さらに追加される

Tokyo - Japan
New York - USA
Bangkok - Thailand
London - UK
Peru - Lima
Peru - Lima

ファイル書き込み “w”

ファイルに書き込み(上書き)はwriteなので、第二引数を”w”。

text_file = open("text.txt", "w") 

ファイルを上書き

外部テキストファイル(text.txt)

Tokyo - Japan
New York - USA
Bangkok - Thailand
London - UK

“w”を使うと記述した内容で指定ファイルを上書きする。

text_file = open("text.txt", "w")

text_file.write("Paris - France")

text_file.close()

結果(text.txt)

Paris - France

新規ファイル作成

新規ファイルを作成するには、新しいファイル名を指定。

text_file = open("text2.txt", "w")

text_file.write("Beijing - China")

text_file.close()

結果(text2.txt)

Beijing - China

新しいファイルが作成されている。

open関数

ファイルを開いてファイル読み込みなどのファイル操作には、open関数(pythonの組み込み関数)を使うことができる。

open関数の書き方

open(ファイル名, モード)

第1引数にファイル名(同一ディレクトリでなければファイルパスを指定)、第2引数でモードオプションを指定。

# 読み込み(デフォルト)
open("textfile.txt", "r")

# 書き込み
open("textfile.txt", "w")

# 追記
open("textfile.txt", "a")

# 上書き編集
open("textfile.txt", "r+")

# クリアにした上で編集
open("textfile.txt", "w+")


# テキストモード(デフォルト)
open("textfile.txt", "t")

# バイナリモード
open("textfile.txt", "b")

コメント