python-for-j277 / files · Lesson 14
Lesson 14 — Files
Text File Handling
Save text to a file and read it back.
Files let a program keep data after it closes. Here you will write text to a file and read it back in.
Writing to a file
file = open("notes.txt", "w")
file.write("First line\n")
file.write("Second line\n")
file.close()How it works
open()opens a file;"w"means write mode, which creates the file and erases anything already in it..write()puts text into the file.\nmeans 'new line', so each line sits on its own..close()saves and closes the file — always do this when writing.
Reading a whole file
file = open("notes.txt", "r")
contents = file.read()
file.close()
print(contents)Output
First line Second line
How it works
"r"means read mode..read()returns the entire contents as one string.- We store it, close the file, then print it.
Reading line by line
file = open("notes.txt", "r")
for line in file:
print(line.strip())
file.close()Output
First line Second line
How it works
- Looping over the file gives you one line at a time.
- Each line includes its
\n, so.strip()removes the extra blank line.
Adding without erasing
file = open("notes.txt", "a")
file.write("Third line\n")
file.close()How it works
"a"means append mode — it adds to the end instead of erasing.- Use
"a"when you want to keep what is already there.
Write mode wipes the file
"w" erases the file's contents before writing. Use "a" if you want to keep the existing text.Three modes to remember
"r" read, "w" write (erases), "a" append (adds on).What you have learned
open(filename, mode)opens a file; modes are"r","w"and"a"..write()adds text;\nstarts a new line..read()reads everything; looping reads line by line..strip()tidies the newline off a line.- Always
.close()the file when you are done.