Pythonメモ:ファイルの作成、書き込み、読み込みのサンプルコード

ファイルに書き込む

#ベター
with open('memo.txt', 'w') as f:
    f.write('this is memo')
    print(f)

#with使用しない場合(非推奨)
f = open('memo.txt', 'w')
f.write('this is memo.')
print(f)
f.close()

ファイルに文字を付け足す場合(append)

f = open('memo.txt', 'a')
f.write('this is memo.')
print(f)
f.close()

ファイルの読み込み

with open('memo.txt', 'r') as f:
    #通常の読み込み
    print(f.read())

    #一文字ずつ読み込む
    while True:
        line = f.readline()
        print(line)
        if not line:
            break

    #特定の塊ごとに読み込む
    while True:
        chunk = 2
        line = f.read(chunk)
        print(line)
        if not line:
            break

ファイルの書き込み+読み込み

with open('memo.txt', 'w+') as f:
    f.write('this is memo')
    print(f)

 

ファイルの読み込み+書き込み

with open('memo.txt', 'r+') as f:
    print(f.read())
    f.write('this is memo')
    print(f.read())

 

seek関数を使って移動

with open('memo.txt', 'r') as f:
    print(f.tell())
    print(f.read(1))
    f.seek(5)
    print(f.read(1))

 

About TIER

TIERは、Global、DX、HRの3軸により 大手企業から中小企業、民間企業から行政まで、海外展開に必要なサービスをワンストップで支援しております。海外マーケティングセールスからデジタルマーケティング、多言語サイトや越境ECサイト制作等の海外向けクリエイティブ制作、グローバル人材採用支援まで幅広く対応しております。お気軽にお問い合わせください。

Check Also

python

Pythonメモ:while文のサンプルコード

繰り返し処理はfor文と今回の …