Lecture 1: File Handling in Python

1. File Access Modes

When opening a file in Python, you need to specify the mode in which you want to open it.

Mode Description File Pointer File Existence
'r' Read (default mode). Opens file for reading. Beginning File must exist
'w' Write. Opens file for writing. Beginning Creates new or truncates existing
'a' Append. Opens file for appending. End Creates new if doesn't exist
'r+' Read and write. Beginning File must exist
'w+' Write and read. Truncates file. Beginning Creates new or truncates existing
'a+' Append and read. End Creates new if doesn't exist
'b' Binary mode (e.g., 'rb', 'wb', 'ab', etc.) - -

2. Basic File Operations

Opening and Closing Files

# Opening a file file = open('example.txt', 'r') # Open in read mode # Perform file operations content = file.read() # Always close the file file.close() # Better way: using 'with' statement (automatically closes file) with open('example.txt', 'r') as file: content = file.read() # File automatically closed after this block

Writing to Files

# Writing to a file (overwrites existing content) with open('output.txt', 'w') as file: file.write('Hello, World!\n') file.write('This is a new line.') # Appending to a file with open('output.txt', 'a') as file: file.write('\nThis line is appended.') # Writing multiple lines lines = ['First line\n', 'Second line\n', 'Third line\n'] with open('lines.txt', 'w') as file: file.writelines(lines)

3. Reading from Files

# Reading entire file content with open('example.txt', 'r') as file: content = file.read() # Reads entire content as string print(content) # Reading line by line with open('example.txt', 'r') as file: for line in file: print(line.strip()) # strip() removes trailing newline # Reading all lines into a list with open('example.txt', 'r') as file: lines = file.readlines() # Returns list of lines # Reading specific number of characters with open('example.txt', 'r') as file: chunk = file.read(100) # Reads first 100 characters print(chunk) # Continue reading next 100 characters next_chunk = file.read(100)

File Pointer Position

with open('example.txt', 'r') as file: # Get current position position = file.tell() print(f"Current position: {position}") # Read first 10 characters content = file.read(10) print(f"Read: {content}") # Get new position position = file.tell() print(f"New position: {position}") # Move to beginning of file file.seek(0) print(f"Position after seek(0): {file.tell()}") # Move to 5th byte from current position file.seek(5, 1) # 1 means from current position print(f"Position after seek(5, 1): {file.tell()}")

4. File Object Methods

Method Description Example
read(size) Reads at most size bytes from the file content = file.read(100)
readline() Reads next line from file line = file.readline()
readlines() Reads all lines into a list lines = file.readlines()
write(string) Writes string to file file.write('text')
writelines(seq) Writes sequence of strings file.writelines(lines)
tell() Returns current file position pos = file.tell()
seek(offset, from) Changes file position file.seek(0)
close() Closes the file file.close()

5. The with Statement

The with statement ensures that the file is properly closed after its suite finishes, even if an exception is raised.

# Without 'with' statement file = open('example.txt', 'r') try: # File operations data = file.read() # More operations... finally: file.close() # This always runs, even if error occurs # With 'with' statement (recommended) with open('example.txt', 'r') as file: data = file.read() # File automatically closed after this block # Even if an exception occurs # Multiple files can be opened in a single 'with' statement with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile: for line in infile: outfile.write(line.upper())

6. Working with Binary Files

# Reading a binary file (e.g., an image) with open('image.jpg', 'rb') as file: binary_data = file.read() # Writing binary data with open('copy.jpg', 'wb') as file: file.write(binary_data) # Working with binary data in chunks chunk_size = 1024 # 1KB chunks with open('large_file.bin', 'rb') as src, \ open('copy.bin', 'wb') as dst: while True: chunk = src.read(chunk_size) if not chunk: break dst.write(chunk)

7. Practical Example: Text File Processing

# Count words in a text file def count_words(filename): word_count = {} with open(filename, 'r') as file: for line in file: words = line.strip().split() for word in words: word = word.lower().strip('.,!?;:"\'()[]{}') if word: word_count[word] = word_count.get(word, 0) + 1 return word_count # Find most common words def most_common_words(filename, n=10): word_count = count_words(filename) return sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:n] # Example usage if __name__ == "__main__": filename = 'sample.txt' common_words = most_common_words(filename) for word, count in common_words: print(f"{word}: {count}")