ファイルへの書き込み

Pythonでは、さまざまな目的でファイルを開くことができます。ファイルを読み込んだり、書き込んだり、さらにはデータを追記することも可能です。これらの操作を行うには、ファイルを異なるモードで開く必要があります。デフォルトのモードは r(読み込み)で、これまで使用してきたものです。

モード

操作

'r'

読み込み(デフォルト)

with open('document.txt', 'r') as f:

'w'

書き込み

with open('document.txt', 'w') as f:

'a'

追記

with open('document.txt', 'a') as f:

'r+'

読み込み+書き込み

with open('document.txt', 'r+') as f:

'x'

新規作成(存在する場合はエラー)

with open('document.txt', 'x') as f:

適切なモードでファイルを開いた後、読み込みや書き込みなどの操作を行うことができます。write() 関数を使ってファイルに書き込むことができます。

with open('document.txt', 'w') as f:
    f.write('This is a written line\n')
    f.write('And the second line!')
    f.write('Continuation is here...')

このプログラムを実行すると、document.txt には2行の内容が含まれます(最初の文字列の末尾にある \n のため)。1つの write() 操作で書き込むこともできますが、説明のために上のプログラムでは複数の write() コマンドを使って開いたファイルに別々の文字列を書き込んでいます。

チャレンジ

入力として2行のテキストが与えられたとき、それらをスペースで区切って output.txt に出力するプログラムを書いてください。

入力

output.txt

hello there

hello there

Constraints

Time limit: 2 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue