何も誇れぬ人生の記録

『ぼくは何も誇れないのが誇りだな』沼田真佑、影裏より

ファイル入出力

def file_upper(infile, outfile):
  with open(infile, 'r') as inf, open(outfile, 'w') as outf:
    up = inf.read().upper()
    outf.write(up)


with open('print-test.txt', 'w') as f:
    print('hello', 'world', file=f)
file_upper('print-test.txt', 'print-test-upper.txt')
with open('print-test-upper.txt', 'r') as f:
    print(f.read() == 'HELLO WORLD\n')

文字の整形

'あいうえお \n'.rstrip() # Out: 'あいうえお'
'あいうえお \n\n'.rstrip('\n) # Out: 'あいうえお '

その応用

with open('text/novel.txt', 'r', encoding='utf-8') as f:
    while True:
        line = f.readline()
        if line == '':
            break
        print(line)

print('------ 末尾の改行文字を削除すると以下のようになります-------')
with open('text/novel.txt', 'r', encoding='utf-8') as f:
    while True:
        line = f.readline()
        if line == '':
            break
        print(line.rstrip('\n'))