Working with files is a common task in programming. Python makes file handling easy with a set of built-in methods that allow reading, writing, and manipulating files.
In this article, we’ll cover all essential file methods provided by Python’s file object, with examples for each.
Opening a File
Before using file methods, you must open a file using the open()
function.
file = open("example.txt", "r") # Modes: 'r', 'w', 'a', 'rb', etc.
Always close the file after operations using
close()
or use awith
block.
File Object Methods
✅ 1. read(size=-1)
Reads and returns up to size
bytes. If no size is specified, reads the whole file.
with open("example.txt", "r") as file:
content = file.read()
print(content)
Output: Contents of the file
✅ 2. readline(size=-1)
Reads a single line from the file. Optionally limit the number of bytes.
with open("example.txt", "r") as file:
line = file.readline()
print(line)
Output: First line of the file
✅ 3. readlines(hint=-1)
Reads all lines and returns them as a list. hint
limits the number of bytes read.
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
Output: ['First line\n', 'Second line\n', 'Third line\n']
✅ 4. write(string)
Writes the given string to the file.
with open("output.txt", "w") as file:
file.write("Hello, world!")
Output: Creates or overwrites output.txt
with "Hello, world!"
✅ 5. writelines(lines)
Writes a list of strings to the file.
lines = ["Line 1\n", "Line 2\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
Output: Writes each line to output.txt
✅ 6. close()
Closes the file. It's good practice to close files explicitly if not using with
.
file = open("example.txt", "r")
file.close()
Output: File is closed (not visible output)
✅ 7. flush()
Flushes the internal buffer, writing data to disk immediately.
with open("output.txt", "w") as file:
file.write("Important data")
file.flush() # Ensures data is written now
Output: Forces write to disk
✅ 8. seek(offset, whence=0)
Moves the file cursor to a specific position.
-
offset
: Number of bytes to move -
whence
: 0 = start, 1 = current, 2 = end
with open("example.txt", "r") as file:
file.seek(5)
print(file.read())
Output: Reads file content starting from byte 5
✅ 9. tell()
Returns the current position of the cursor in the file.
with open("example.txt", "r") as file:
file.read(10)
print(file.tell())
Output: 10
(if 10 bytes were read)
✅ 10. truncate(size=None)
Resizes the file to the given size
. If no size is given, truncates at current position.
with open("output.txt", "r+") as file:
file.truncate(5)
Output: Cuts the file content to the first 5 bytes
✅ 11. fileno()
Returns the file descriptor (an integer).
with open("example.txt", "r") as file:
print(file.fileno())
Output: File descriptor number (e.g., 3
, 4
)
✅ 12. isatty()
Returns True
if the file is connected to a terminal device.
with open("example.txt", "r") as file:
print(file.isatty())
Output: False
(files are usually not TTYs)
Summary Table
Method | Description |
---|---|
read() |
Reads entire file or up to specified bytes |
readline() |
Reads one line |
readlines() |
Reads all lines into a list |
write() |
Writes a string |
writelines() |
Writes a list of strings |
close() |
Closes the file |
flush() |
Flushes internal buffer |
seek() |
Moves the cursor to a new position |
tell() |
Returns the current cursor position |
truncate() |
Truncates the file to a given size |
fileno() |
Returns the file descriptor number |
isatty() |
Checks if file is a terminal (TTY) |
File Modes
Mode | Description |
---|---|
'r' |
Read (default) |
'w' |
Write (overwrites file) |
'a' |
Append |
'r+' |
Read and write |
'b' |
Binary mode (e.g., 'rb' , 'wb' ) |
'x' |
Create file, fail if exists |
Best Practices
-
Always use
with open(...) as file:
to automatically close files. -
Use
try-except
for error handling during file operations. -
Be cautious when using
'w'
mode — it overwrites files.
Final Thoughts
Python's file methods are powerful and easy to use for reading, writing, and managing file data. Whether you're logging results, processing data, or reading configuration files, understanding these methods is essential for effective Python programming.