なんだかGoodVibes

日々の勉強メモです。

【Python】ファイルの読み書き

こんにちは。
本日はPythonメモです。

ファイルの読み込み

sample.txtを用意しておきます。
内容は以下のようにしておきます。

Hello
World

では、このファイルを読み込みます。

read()
with open('./sample.txt', encoding='utf-8') as f:
    c = f.read()
    print(c)

実行結果は以下のようになります。

Hello
World

read()を使用した場合は、ファイル全体を文字列として取得します。


readline()
with open('./sample.txt', encoding='utf-8') as f:
    c = f.readline()
    print(c)

実行結果は以下です。

Hello

readline()を使用した場合は、1行目のみを取得します。


readlines()
with open('./sample.txt', encoding='utf-8') as f:
    c = f.readlines()
    print(c)

実行結果は以下です。

['Hello\n', 'World\n']

readlines()を使用した場合は、行ごとのリストで取得します。


ファイルの書き込み

sample.txtを用意しておきます。
内容は以下のようにしておきます。

Hello
World
上書き(mode='w')

ファイルが存在しない場合はファイルを作成して書き込みます。
ファイルが存在する場合、上書きで書き込みます。

with open('./sample.txt', mode='w', encoding='utf-8') as f:
    c = f.write('hello')

実行後のsample.txtの内容は以下です。

hello


追記(mode='a')
with open('./sample.txt', mode='a', encoding='utf-8') as f:
    c = f.write('hello')

実行後のsample.txtの内容は以下です。

Hello
World
hello



以上です。