Text files · Arquivos de texto
Why files?
- Variables vanish when a program ends. A file keeps data on disk.
- Files let you save results and read them back later.
- They also hold more data than you would type by hand.
Por que arquivos?
- Variáveis desaparecem quando um programa termina. Um arquivo mantém os dados no disco.
- Arquivos permitem salvar resultados e lê-los novamente mais tarde.
- Eles também armazenam mais dados do que você digitaria manualmente.
Open, use, close
open(name, mode)opens a file. The mode says what you will do."r"reads,"w"writes a fresh file (replacing any old text),"a"adds to the end.- Every file you open must be closed when you finish.
Abrir, usar, fechar
open(name, mode)abre um arquivo. O modo diz o que você fará."r"lê,"w"escreve um novo arquivo (substituindo qualquer texto antigo),"a"adiciona ao final.- Todo arquivo aberto deve ser fechado quando terminar.
The with block
with open(...) as f:opens the file and closes it for you.- All the work goes in the indented block.
- This is the safest way — the file is never left open.
O bloco with
with open(...) as f:abre o arquivo e o fecha por você.- Todo o trabalho vai no bloco recuado.
- Esta é a forma mais segura — o arquivo nunca fica aberto.
with open("greeting.txt", "w") as f:
f.write("Hi there\n")
with open("greeting.txt", "r") as f:
print(f.read())
Reading the lines
f.read()returns the whole file as one string.for line in f:reads it one line at a time.- Each line keeps its newline, so use
line.strip()to remove it.
Lendo as linhas
f.read()retorna o arquivo inteiro como uma única string.for line in f:lê uma linha de cada vez.- Cada linha mantém sua nova linha, então use
line.strip()para removê-la.
with open("fruit.txt", "w") as f:
f.write("apple\npear\n")
with open("fruit.txt", "r") as f:
for line in f:
print(line.strip())
In Cambridge pseudocode
- The exam uses
OPENFILE,WRITEFILE,READFILE, andCLOSEFILE.
Em pseudocódigo do Cambridge
- O exame usa
OPENFILE,WRITEFILE,READFILEeCLOSEFILE.
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
OPENFILE "notes.txt" FOR READ
READFILE "notes.txt", line
CLOSEFILE "notes.txt"
OUTPUT line
Common mistakes
- Use
with open(...) as f:so the file closes itself. "w"erases the file first;"a"adds to the end.
Erros comuns
- Use
with open(...) as f:para que o arquivo se feche sozinho. "w"apaga o arquivo primeiro;"a"adiciona ao final.
Now you try
- This playground keeps files between runs, so write the file first, then read it in the same task.
- Press Check answer to test your code.
Agora você tenta
- Este playground mantém arquivos entre execuções, então escreva o arquivo primeiro, depois leia-o na mesma tarefa.
- Clique em Check answer para testar seu código.
Reading a file · Lendo um arquivo
A file is used in three steps: open, read, close. · Um arquivo é usado em três passos: abrir, ler, fechar.
In one run: write the two lines Hello and · e World to a file called notes.txt, then open it again, read it, and print what you read. · Em uma execução: escreva as duas linhas Hello e World em um arquivo chamado notes.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.
Write three lines to a file, then read it back and count the lines with a loop. Store the count in count (the answer is 3). · Escreva três linhas em um arquivo, depois leia-as de volta e conte as linhas com um loop. Armazene a contagem em count (a resposta é 3).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write the numbers 10, 20, 30 to a file, one per line. Then read them back, convert each line with int(...), and add them up in total (the answer is 60). · Escreva os números 10, 20, 30 em um arquivo, um por linha. Depois 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.