Python File I/O: Mastering File Operations, Reading, Writing, and Management
Python File I/O
Learn how to open, read, write, and close files in Python with clear examples and best‑practice techniques.
Video: Reading and Writing Files in Python
Files
Files are named locations on disk that store data persistently. Because RAM is volatile, we rely on files to keep information between program executions.
When interacting with a file, the typical sequence is: open → read/write → close.
Opening Files in Python
Python’s built‑in open() function returns a file object that you can use to perform I/O operations. The function’s signature is:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Key points:
modecontrols the operation:r(read),w(write, truncates),a(append),x(create exclusively).t(text) is the default;b(binary) returnsbytesobjects.+allows simultaneous reading and writing.- Always specify
encodingwhen dealing with text to avoid platform‑dependent defaults (e.g.,cp1252on Windows,utf‑8on Linux).
| Mode | Description |
|---|---|
r | Read (default) |
w | Write; creates new or truncates existing |
x | Exclusive creation; fails if file exists |
a | Append; creates if missing |
t | Text mode (default) |
b | Binary mode |
+ | Read and write |
f = open("test.txt") # r/rt
f = open("test.txt", "w") # write
f = open("img.bmp", "r+b") # read/write binary
Because a is a character, it does not equate to the number 97 unless encoded. Explicitly set encoding='utf-8' for text files.
f = open("test.txt", mode='r', encoding='utf-8')
Closing Files in Python
Properly closing a file releases system resources. The close() method is straightforward, but using a context manager is the safest pattern.
with open("test.txt", encoding='utf-8') as f:
# perform file operations
pass
The context manager guarantees closure even if an exception occurs. If you open a file manually, wrap it in a try...finally block.
try:
f = open("test.txt", encoding='utf-8')
# operations
finally:
f.close()
Writing to Files in Python
Use w, a, or x mode to write. w overwrites existing content; a preserves it.
The write() method accepts a string (or bytes for binary) and returns the number of characters written.
with open("test.txt", "w", encoding='utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
Remember to include newline characters to separate lines.
Reading Files in Python
Open with r mode. The read() method accepts an optional size argument; omitting it reads to EOF.
f = open("test.txt", "r", encoding='utf-8')
print(f.read(4)) # 'This'
print(f.read(4)) # ' is '
print(f.read()) # remaining content
f.close()
Move the cursor with seek() and query its position with tell():
print(f.tell()) # current position
f.seek(0) # rewind
print(f.read()) # read all
Iterate over lines efficiently:
for line in f:
print(line, end='')
Alternatively, readline() and readlines() provide line‑by‑line access.
Python File Methods
Below is a concise reference for the most common file methods in text mode.
| Method | Description |
|---|---|
| close() | Close the file. |
| detach() | Detach the underlying binary buffer. |
| fileno() | Return the file descriptor. |
| flush() | Flush the write buffer. |
| isatty() | Check if the stream is interactive. |
| read(n) | Read up to n characters; None reads to EOF. |
| readable() | Is the stream readable? |
| readline(n=-1) | Read a single line, up to n characters. |
| readlines(n=-1) | Return a list of lines, up to n characters. |
| seek(offset, from_=SEEK_SET) | Move cursor to offset from from_ (start, current, end). |
| seekable() | Can the stream support random access? |
| tell() | Get current cursor position. |
| truncate(size=None) | Resize file to size bytes. |
| writable() | Is the stream writable? |
| write(s) | Write string s; returns number of characters written. |
| writelines(lines) | Write an iterable of strings. |
Python
- Mastering C Input and Output (I/O): scanf() and printf() Explained
- Python File I/O: Mastering File Operations, Reading, Writing, and Management
- Java Input/Output Streams: Fundamentals and Types
- File Operations in C# – A Practical Guide
- Copy Files in Python with shutil.copy() and shutil.copystat()
- How to Rename Files and Directories in Python with os.rename() – Step-by-Step Guide
- Creating ZIP Archives in Python: From Full Directory to Custom File Selection
- Mastering File I/O in C: Creating, Opening, and Managing Files
- Mastering C# File I/O: Reading, Writing, and Managing Streams
- Python File I/O: Mastering Input and Output Operations