Text files · Arquivos de texto
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.
Arquivos mantêm dados
- Variáveis desaparecem quando um programa termina; um arquivo armazena dados para que persistam.
- A prova cobre leitura e escrita em arquivos de texto.
- Trabalhe em três etapas: abrir, ler ou escrever, depois fechar.
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.
Escrevendo em um arquivo
open(name, "w")abre um arquivo para escrita ("w"sobrescreve o que estava lá).withfecha o arquivo automaticamente quando o bloco termina.\ninicia uma nova linha no arquivo.
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.
Lendo um arquivo
open(name, "r")abre um arquivo para leitura..read()puxa todo o conteúdo como uma única string.
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.
Lendo linha por linha
- Loopar sobre o arquivo fornece uma linha de cada vez — útil para somar ou contar.
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.
Na prova: manipulação de arquivos
- Pseudocódigo abre um arquivo para um modo, lê ou escreve, depois o fecha.
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.
Erros comuns
- Abrir, depois ler ou escrever, depois fechar o arquivo.
- Uma linha lida ainda carrega seu caractere de nova linha.
Now you try
- Write a file, then open it again to read it back.
- Press Check answer to test your code.
Agora você tenta
- Escreva um arquivo, depois abra-o novamente para lê-lo de volta.
- Clique em Check answer para testar seu código.
Using a file · Usando um arquivo
A file is used in three steps: open, read or write, close. · Um arquivo é usado em três etapas: abrir, ler ou escrever, fechar.
In one run: write the line Cambridge to a file called school.txt, then open it again, read it, and print what you read. · Em uma execução: escreva a linha Cambridge em um arquivo chamado school.txt, depois abra-o novamente, leia-o e print o que você leu.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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). · O código inicial escreve três linhas para um arquivo. Leia-o de volta e conte as linhas com um laço. Armazene a contagem em count (a resposta é 3).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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). · O código inicial escreve 10, 20, 30 para um arquivo, um por linha. Leia-os de volta, converta cada linha com int(...), e some-os em total (a resposta é 60).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.