Master Python File I/O: Open, Read, Write, and Manage Files Efficiently
This article explains Python's file handling basics, covering what files are, how to open them with the open() function, various access modes, common file object methods such as read, readline, readlines, write, tell, seek, and the use of the with statement for safe resource management, plus code examples.
1. What is a file?
A file stores data so that a program can reuse it later without recreating the content.
2. How to open a file?
Python provides the built‑in open() function for reading and writing files. The typical workflow is three steps: open, operate, close.
open syntax
The open() function returns a file object (file handle).
Basic syntax: f = open(filename, mode) filename : string containing the file name or path.
mode : file access mode, default is read‑only r.
Example:
# Open a file
f = open("1.txt", "w")
f.write("Python is a great language.
Python!!
")
# Close the file
f.close()Result: the text is written into 1.txt.
3. Access modes
r : read‑only, pointer at start (default).
w : write‑only, overwrite if exists or create new.
a : append, pointer at end, create if not exist.
rb : binary read‑only, pointer at start.
wb : binary write‑only, overwrite or create.
ab : binary append.
r+ : read/write, pointer at start.
w+ : read/write, overwrite or create.
a+ : read/write, pointer at end, create if not exist.
rb+ : binary read/write, pointer at start.
wb+ : binary read/write, overwrite or create.
ab+ : binary append/read/write, pointer at end, create if not exist.
To read a non‑UTF‑8 file, pass the encoding argument, e.g., open('gbk.txt', 'r', encoding='gbk'). If decoding fails, you can use the errors='ignore' parameter.
f = open('gbk.txt', 'r', encoding='gbk', errors='ignore')4. File object operations
Common methods:
1. f.read(size)
Read up to size bytes; if omitted or negative, reads the whole file.
f = open("1.txt", "r")
content = f.read()
print(content)
f.close()2. f.readline()
Read a single line, including the newline character.
f = open("1.txt", "r")
line = f.readline()
print(line)
f.close()3. f.readlines()
Read all lines into a list.
f = open("1.txt", "r")
lines = f.readlines()
print(lines)
f.close()4. Iterate over a file
# Open a file
f = open("1.txt", "r")
for line in f:
print(line, end='')
# Close the file
f.close()5. f.write()
Write a string to the file.
f = open("/tmp/foo.txt", "w")
f.write("Python is a great language.
I love Python!!
")
f.close()6. f.tell()
Return the current byte offset of the file pointer.
7. f.seek(offset, from_what)
Move the file pointer. from_what can be 0 (start), 1 (current), or 2 (end).
f = open("1.txt", "rb+")
f.write(b"1232312adsfalafds")
print(f.tell())
print(f.seek(5, 0))
print(f.read(1))
print(f.seek(-3, 2))
print(f.read(1))Result:
8. f.close()
Close the file and release system resources.
5. The with statement
The with statement provides a context manager that automatically closes the file, even if an exception occurs.
with open('test.txt', 'w') as f:
f.write('Hello, world!')You can open multiple files in a single with block:
with open('1') as obj1, open('2', 'w') as obj2:
data = obj1.read()
obj2.write(data)6. Summary
This article introduces Python file handling fundamentals, demonstrating how to open files, use various access modes, perform common file object operations, and safely manage resources with the with statement.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
