File handling is essential for reading data from files, storing output, and working with external data sources in Python.
Opening a File
The open() function is used to open files in Python. It takes two arguments:
- File name: The name of the file to open.
- Mode: Specifies how the file should be opened (e.g., for reading, writing, or appending).
Example:
f = open('myfile.txt', 'r') # Opens the file in read modeFile Open Modes
| Mode | Description |
|---|---|
'r' |
Open for reading (default). Raises an error if the file does not exist. |
'w' |
Open for writing. Creates a new file or overwrites an existing file. |
'a' |
Open for appending. Creates a new file if it doesn’t exist, and appends to the end of the file. |
'x' |
Open for exclusive creation. Raises an error if the file already exists. |
't' |
Text mode (default). |
'b' |
Binary mode (used for non-text files like images, videos, etc.). |
Reading from a File
-
Using
read(): Reads the entire content of a file as a string.with open('myfile.txt', 'r') as f: content = f.read() print(content) -
Using
readline(): Reads a single line from the file.with open('myfile.txt', 'r') as f: line = f.readline() print(line) -
Using
readlines(): Reads all lines from the file and returns a list of strings.with open('myfile.txt', 'r') as f: lines = f.readlines() print(lines)
Writing to a File
-
Using
write(): Writes a string to a file. Overwrites the file if it exists.with open('myfile.txt', 'w') as f: f.write('Hello, world!') -
Using
writelines(): Writes multiple lines (provided as a list or iterable) to a file.lines = ['Line 1\n', 'Line 2\n', 'Line 3\n'] with open('myfile.txt', 'w') as f: f.writelines(lines)
Appending to a File
To add content to the end of an existing file, use append mode ('a').
Example:
with open('myfile.txt', 'a') as f:
f.write('This will be appended.\n')Closing a File
Always close a file after working with it to release resources. Use close() or the with statement for automatic closure.
Manual closure:
f = open('myfile.txt', 'r')
# Do something
f.close()Automatic closure using with:
with open('myfile.txt', 'r') as f:
content = f.read()File Position: seek() and tell()
seek(offset): Moves the file's position to a specific byte.
Example:
with open('myfile.txt', 'r') as f:
f.seek(5) # Move to the 5th byte (skips the first 5 characters)
data = f.read()
print(data)tell(): Returns the current position of the file pointer.
with open('myfile.txt', 'r') as f:
print(f.tell()) # Prints the current positionTruncating a File: truncate()
Shortens a file to a specified length (in bytes). If no length is provided, it truncates the file from the current position.
It modifies the file permanently.
Example:
with open('myfile.txt', 'w') as f:
f.write('Hello World!')
f.truncate(5) # Keeps only the first 5 bytes
with open('myfile.txt', 'r') as f:
print(f.read()) # Output: HelloBest Practices
- Use
withfor safe file handling: Automatically closes the file even in case of exceptions. - Use appropriate modes: Choose the correct mode to avoid unintentional data loss.
- Validate file paths: Check for file existence and permissions before performing operations.
👉 Next tutorial: Python Virtual Environment