Reading Files in Python
Reading files means opening an existing file and getting its contents into your Python program.
Key Points:
- Opening a file: Use the
open()
function with the file path and mode 'r' for reading - Reading methods:
read()
- reads the entire file as a single stringreadline()
- reads one line at a timereadlines()
- reads all lines into a list
- Closing the file: Always close files with
close()
or usewith
statement for automatic closing - Example:
with open('data.txt', 'r') as file: content = file.read() print(content)
- Use cases: Reading data files, configuration files, or any stored information
Writing Files in Python
Writing files means creating new files or modifying existing ones by adding data from your Python program.
Key Points:
- Opening modes:
- 'w' - write mode (overwrites existing file)
- 'a' - append mode (adds to end of file)
- 'x' - exclusive creation (fails if file exists)
- Writing methods:
write()
- writes a string to the filewritelines()
- writes a list of strings
- Important: Writing mode creates the file if it doesn't exist
- Example:
with open('output.txt', 'w') as file: file.write("Hello, World!")
- Use cases: Saving program results, logging data, creating reports
Important Notes
- - Always specify the correct file path (absolute or relative)
- - Remember file handling can cause errors (use try-except blocks)
- - The
with
statement is preferred as it automatically closes files - - For engineering applications, you might work with CSV, JSON, or other special file formats
Understanding Read Functions in Python
When working with files in Python, there are three main methods to read content from a file: read()
, readline()
, and readlines()
. Each serves a different purpose.
1. read()
- What it does: Reads the entire content of the file as a single string
- When to use: When you need all file content at once (for small files)
- Example:
with open('data.txt', 'r') as file: content = file.read() print(content)
- Key points:
- - Returns everything as one big string
- - Can specify size:
read(100)
reads first 100 characters - - Not memory efficient for very large files
2. readline()
- What it does: Reads one line at a time from the file
- When to use: When you want to process a file line by line
- Example:
with open('data.txt', 'r') as file: line = file.readline() while line: print(line.strip()) # strip() removes newline characters line = file.readline()
- Key points:
- - Each call reads the next line
- - Returns empty string when end of file is reached
- - Good for memory efficiency with large files
3. readlines()
- What it does: Reads all lines into a list where each line is a list item
- When to use: When you need all lines separately but want them in a list
- Example:
with open('data.txt', 'r') as file: lines = file.readlines() for line in lines: print(line.strip())
- Key points:
- - Returns a list where each element is one line
- - Includes newline characters at end of each string
- - Not ideal for very large files (stores everything in memory)
Comparison Table
Method | Returns | Memory Use | Best For |
---|---|---|---|
read() | Single string | High (all content) | Small files |
readline() | One line at a time | Low | Large files |
readlines() | List of strings | High (all lines) | Medium files |
Exam Tips
- - Remember to always open files in correct mode ('r' for reading)
- - Use
with
statement for automatic file closing - readline()
is best for memory efficiency with large files- - For processing files, you can also directly iterate over the file object:
for line in file: # memory efficient like readline() print(line)
- - Don't forget to handle file exceptions in real applications
Understanding Write Functions in Python
When writing to files in Python, we primarily use two methods: write()
and writelines()
. These help store data from your program into files.
1. write()
- What it does: Writes a single string to the file
- When to use: When you need to write individual strings or combine data before writing
- Example:
with open('output.txt', 'w') as file: file.write("Hello, World!\n") file.write("This is a second line.")
- Key points:
- - Accepts only string as input (convert numbers using str())
- - Doesn't automatically add newlines (\n) - you must include them
- - Returns the number of characters written
- - Can be called multiple times on the same file
2. writelines()
- What it does: Writes multiple strings from a list/iterable to the file
- When to use: When you have a collection of strings to write at once
- Example:
lines = ["First line\n", "Second line\n", "Third line\n"] with open('output.txt', 'w') as file: file.writelines(lines)
- Key points:
- - Accepts an iterable (list, tuple, etc.) of strings
- - Does NOT automatically add newlines between items
- - More efficient than multiple write() calls for large collections
- - Doesn't return any value (None)
Comparison Table
Method | Input Type | Adds Newline? | Best For |
---|---|---|---|
write() | Single string | No (must add \n manually) | Individual strings or formatted output |
writelines() | List/iterable of strings | No (must include \n in strings) | Writing pre-prepared collections of lines |
Important Notes
- File Modes Matter:
- 'w' - overwrites existing file
- 'a' - appends to existing file
- 'x' - creates new file (fails if exists)
- Always convert numbers to strings before writing:
file.write(str(42))
- For structured data, consider JSON or CSV modules instead
- Large writes are more efficient than many small writes
- Remember to close files or use
with
statements
Examples
Example 1: Writing sensor data
sensor_readings = [23.5, 24.1, 25.0, 24.8] with open('sensor.log', 'a') as file: # append mode for reading in sensor_readings: file.write(f"{reading:.2f}\n") # formatted to 2 decimal places
Example 2: Saving multiple calculations
results = [f"Calculation {i}: {i**2}\n" for i in range(1, 6)] with open('calculations.txt', 'w') as file: file.writelines(results)
Understanding File Pointer
When you open a file in Python, there's an invisible "pointer" that keeps track of where you are in the file. This pointer moves automatically as you read or write.
seek() Function
The seek()
function lets you move this pointer to any position in the file.
Syntax:
file.seek(offset, whence)
Parameters:
- offset: Number of bytes to move (can be positive or negative)
- whence: Reference point for the seek (optional, default is 0)
0
- Beginning of file (default)1
- Current position2
- End of file
Examples:
# Move to 5th byte from start file.seek(5) # Move 10 bytes forward from current position file.seek(10, 1) # Move to 5 bytes before end of file file.seek(-5, 2)
tell() Function
The tell()
function tells you the current position of the file pointer.
position = file.tell() print(f"Current position: {position}")
Practical File Operations with seek()
1. Reading from specific positions
with open('data.bin', 'rb') as file: # Jump to 100th byte file.seek(100) data = file.read(50) # Read 50 bytes from position 100
2. Updating parts of a file
with open('records.txt', 'r+') as file: # Go to start of 3rd record (assuming fixed length) file.seek(2 * RECORD_SIZE) file.write("New data") # Overwrite existing data
3. Appending and then reading
with open('log.txt', 'a+') as file: file.write("New log entry\n") file.seek(0) # Rewind to start content = file.read()
Important Note
- seek()
works in bytes, not lines or characters- - Text vs Binary mode differences:
- In text mode, offsets should be from
file.tell()
or 0 - Binary mode allows arbitrary seeking
- In text mode, offsets should be from
- - Negative offsets only work when
whence
is 1 or 2 - - Remember file modes:
- 'r+' - read and write (file must exist)
- 'w+' - read and write (overwrites file)
- 'a+' - read and append
Exam Practice Question
What will be the output of this code?
with open('test.txt', 'w+') as f: f.write("HelloWorld") f.seek(5) print(f.read(3))
Answer: "Wor" (seeks to position 5, then reads 3 characters)
No comments:
Post a Comment