Alterna · учебный материал
Reading and recording files
40.3: Reading and recording files. Short theory, one example, and Python stepway.
Что в этом материале
- How it works.
- One example in execution
- Remember
Содержание и основные понятия
At the EEG, files are provided for individual tasks. The program should open the exact name, read the format and not mix the data with line translations.
substance and practice
Grade 11
EEG No. 24
01
How it works.
The file is an external data stream. The program must clearly know the name, coding, string format and behavioral rule for an empty or damaged entry.
with.
The context manager guarantees that the file will be closed even if it is wrong.
read.
Reads the entire text; it fits the same line or moderate volume.
Lined up.
For line in file handles the stream without storing the entire file.
Recording.
The 'w' mode creates or purifies the file; 'a' completes at the end.
02
One example in execution
Start the short program and go over the lines. The visualiser only shows the code, current line, variables and output.
Point out.
encoding='utf-8'
because the default coding depends on the platform.
strip()
it removes the translation of the line, but it also removes gaps on the edges, which is not appropriate for any format. For big data, you prefer cutting and save only the right aggregates.
FileNotFoundError
means that the file name or work folder did not match the condition.
Algorithm map
Read from left to right, then run the code.
1
Start
2
Take the next line
3
Delete Line Translation
4
Is that a good line?
5
Transform and Save
03
Remember
First, determine if empty lines are allowed.
Do not call max/min on an empty list of candidates without condition or guarantee.
Don't set your computer's absolute path on the exam program.
Syntax of this page
open(name, mode='r', encoding='utf-8')
Opens the file; a clear UTF-8 translates the reading.
with open(...) as file
Close the file automatically after the block.
file.read()
Reads all the remaining text in the same line.
file.readline()
Reads one line, including \n if available.
for line in file
Reads the file lined up.
file.write(text)
Writes down the row and returns the number of symbols; add the symbol \n clearly.
strip
Deletes the edges of the line before ent or comparison.
int
It converts an unforgettable number line into an int.
FileNotFoundError
An exception if the file is not found.
print
It takes the result away, not it goes back to the file.