File Operations
Opening a File
Besides computation, a computer must be able to store data, usually in files. Python directly provides file I/O (Input/Output) functions that make reading and writing convenient.
The open() function opens a file. If no mode is specified, it defaults to r (read-only mode).
open(file, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None)| Mode | Description |
|---|---|
r | Open read-only; this is the default |
w | Open for writing; overwrite an existing file or create a missing file |
x | Create a new file for writing; fail if it already exists |
a | Append content |
b | Binary mode |
t | Text mode (default) |
+ | Open for updating (reading and writing) |
Opening a nonexistent path in read-only mode raises FileNotFoundError.
File operations
file = open(file="data.txt", mode="w")
print("File name: %s" % file.name)
print("Mode: %s" % file.mode)
print("Status: %s" % file.closed)
print("Closing...")
file.close()
print("Status: %s" % file.closed)Output
File name: data.txt
Mode: w
Status: False
Closing...
Status: TrueReading and Writing Files
After opening a file with open(), use the resulting file object to read and write.
A file opened for reading can be read line by line in a loop. Python also simplifies this: the file object itself is iterable, and each iteration reads one line separated by newline characters.
| Method | Description |
|---|---|
close() | Close the file resource |
fileno() | Get the file descriptor |
flush() | Force the buffer to flush |
read(n=-1) | Read data; by default, read everything |
readlines(hint=-1) | Read all data lines |
readline(size=-1) | Read one line |
truncate(size=None) | Truncate the file |
writable() | Check whether writing is allowed |
write(s) | Write to the file |
writelines(lines) | Write a sequence of strings |
Since developers must ultimately close every file object, a with statement can close resources automatically. Managing resource acquisition and release with with is an important Python technique that greatly simplifies code structure.
Reading a file
with open(file="data.txt", mode="r", encoding="utf-8") as file:
for line in file:
print(line, end='')data.txt
Alice 16
Bob 17
Terry 21Output
Alice 16
Bob 17
Terry 21Writing a file
with open(file="data.txt", mode="w", encoding="utf-8") as file:
info = {"Alice": 16, "Bob": 17, "Terry": 21}
for name, age in info.items():
file.write("%s %d\n" % (name, age))Output: data.txt
Alice 16
Bob 17
Terry 21A file, a cursor and five opening modes
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Read, select and append a summary
scores.txt contains the three records below. Write a Python program that reads each line, writes records with a score of at least 18 to selected.txt, replacing any old output, then reopens it in append mode to add Selected: 2. Use UTF-8 and with; keep the input unchanged.
Maya 19
Noah 16
Iris 22