Learn Python
>>> file_handling.file_read_write

Reading and Writing Files in Python

#concept

Reading and writing files lets a program persist data beyond its own runtime, or process data that already exists on disk. Python's built-in open() function is the entry point for both: it returns a file object that can then be read from or written to, depending on the mode it was opened with.

#how it works
1

open("filename", mode)

Opens a file, returning a file object to work with.

2

.write("text")

Writes text to the file, if it was opened in a writable mode.

3

.read()

Reads the file's entire contents at once, returning it as one string.

4

.readline() and .readlines()

Read one line at a time, or every line into a list of strings.

5

.close() releases the file

Frees the underlying system resource once finished — though with, covered next, handles this automatically and more safely.

#example
file = open("notes.txt", "w")
file.write("Hello, file!\nSecond line.")
file.close()
 
file = open("notes.txt", "r")
content = file.read()
file.close()
 
print(content)
Output
Hello, file!
Second line.
1open("notes.txt", "w") opens the file in write mode, creating it if it doesn't already exist, or overwriting it if it does.
2write(...) writes the given text, including an embedded newline, then .close() saves and releases the file.
3Opening the file again in read mode ("r") and calling .read() retrieves everything just written, as one string.
4Printing that string shows the two lines exactly as they were written, since the embedded newline created a genuine line break inside the file.
#use cases
Saving a program's results or settings so they persist after the program ends
Reading configuration or data files that already exist on disk
Building simple logs, notes, or reports that get written to a plain text file
Processing large text files line by line, without loading the entire thing into memory at once using .readline()

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.