File Reading Techniques
Python's file objects provide several method for retrieving data, each suited for different scenarios.
Byte-Level Reading with read()
The read() method fetches content in byte-sized chunks. When called without arguments, it retrieves all remaining data. With a positive integer, it reads exactly that many bytes, maintaining a persistent cursor position.
with open('sample.dat', 'r', encoding='utf-8') as stream:
initial_chunk = stream.read(3)
print(f"First 3 bytes: {initial_chunk}")
subsequent_data = stream.read()
print(f"Remaining content: {subsequent_data}")
Line-by-Line Processing with readline()
For sequential line processing, readline() extracts a single line including its newline character.
with open('config.txt', 'r') as config_handler:
header = config_handler.readline()
while header:
process(header) # hypothetical processing function
header = config_handler.readline()
Batch Line Reading with readlines()
The readlines() method consumes the entire file and returns a list of lines. The optional hint parameter limits reading based on approximate byte count.
with open('data.csv', 'r') as csv_file:
first_five_kb = csv_file.readlines(hint=5120)
for record in first_five_kb:
print(record.rstrip())
Single String Output with write()
The write() method outputs a string and returns the number of bytes successfully written.
with open('output.log', 'w') as log:
message = "System initialized\n"
bytes_count = log.write(message)
print(f"Logged {bytes_count} bytes")
Mlutiple Line Output with writelines()
Unlike its name suggests, writelines() doesn't automatically add newline characters. It writes an iterable of strings verbatim.
entries = ["Entry 1\n", "Entry 2\n", "Entry 3"]
with open('journal.txt', 'w') as journal:
journal.writelines(entries)
File Position Control
Querying Position with tell()
The tell() method reports the current byte offset from the file's beginning.
with open('archive.bin', 'rb') as binary_file:
print(f"Starting position: {binary_file.tell()}")
binary_file.read(8)
print(f"After reading 8 bytes: {binary_file.tell()}")
Seeking with seek()
The seek() method repositions the file cursor. It accepts an offset and a reference point: 0 for file start, 1 for current location, or 2 for file end.
with open('document.txt', 'r') as doc:
# Jump to 5 bytes from start
new_pos = doc.seek(5, 0)
print(f"New position: {new_pos}")
print(f"Verification: {doc.tell()}")
# Read from new position
content = doc.read(10)
print(f"Content at position 5: {content}")
Directory and File System Management
System-level file operations require the os module.
import os
File Removal
Permanently delete files using remove():
os.remove('temporary.cache')
File Renaming
Rename files or move them between directories with rename():
os.rename('draft.txt', 'final.txt')
Directory Creation
Create single-level directories using mkdir():
os.mkdir('reports/2024')
Directory Removal
Remove empty directories with rmdir():
os.rmdir('old_projects')
Working Directory Query
Retrieve the current working directory path:
working_dir = os.getcwd()
print(f"Current directory: {working_dir}")