Text files · テキストファイル
Files keep data
- Variables vanish when a program ends; a file stores data so it lasts.
- The exam covers reading from and writing to text files.
- Work in three steps: open, read or write, then close.
ファイルがデータを保持する
- プログラム終了時に変数は消滅するが、ファイルはデータを保存して持続させる。
- 試験ではテキストファイルからの読み出しと書き込みを扱う。
- 3つの手順で行う:開く、読み出しまたは書き込み、そして閉じる。
Writing to a file
open(name, "w")opens a file for writing ("w"overwrites what was there).withcloses the file automatically when the block ends.\nstarts a new line in the file.
ファイルへの書き込み
open(name, "w")はファイルを開き、書き込みモードにする("w"は既存の内容を上書きする)。withはブロック終了時にファイルを自動的に閉じる。\nはファイル内に改行を追加する。
with open("notes.txt", "w") as f:
f.write("Hello\n")
f.write("World\n")
Reading a file
open(name, "r")opens a file for reading..read()pulls in the whole contents as one string.
ファイルの読み出し
open(name, "r")はファイルを開き、読み出しモードにする。.read()は全内容を一文字列として読み込む。
with open("notes.txt", "r") as f:
text = f.read()
print(text)
Reading line by line
- Looping over the file gives one line at a time — handy for totalling or counting.
各行を順に読み込む
- ファイルに対してループを回すと1行ずつ取得でき、合計やカウントに便利である。
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
In the exam: file handling
- Pseudocode opens a file for a mode, reads or writes, then closes it.
試験におけるファイル操作
- 疑似コードでは、ファイルを開いてモードを指定し、読み出しまたは書き込みを行って、最後に閉じる。
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
Common mistakes
- Open, then read or write, then close the file.
- A line you read still carries its newline character.
よくあるミス
- 開いた後、読み出しまたは書き込みを行い、閉じる。
- 読み取った行には、改行文字がまだ含まれています。
Now you try
- Write a file, then open it again to read it back.
- Press Check answer to test your code.
あなたも試してみよう
- ファイルに書き込んだ後、再度開いて読み戻すことができる。
- 回答を確認 を押してコードを試してください。
Using a file · ファイルの使用
A file is used in three steps: open, read or write, close. · ファイル操作は3つの手順で行います:開く、読み書き、閉じる。
In one run: write the line Cambridge to a file called school.txt, then open it again, read it, and print what you read. · 1回の実行で、行Cambridgeをファイルschool.txtに書き込み、次に再び開いて読み込み、printした内容を表示します。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
The starter writes three lines to a file. Read it back and count the lines with a loop. Store the count in count (the answer is 3). · スターターがファイルに3行を書き込みます。それを読み出してループで行数を数え、その数を count に格納してください(答えは 3 です)。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
The starter writes 10, 20, 30 to a file, one per line. Read them back, convert each line with int(...), and add them up in total (the answer is 60). · スターターがファイルに 10, 20, 30 を1行ずつ書き込みます。それらを読み出し、各ラインを int(...) で変換して total に加算してください(答えは 60 です)。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。