Python File Operations: Opening, Reading, Writing, and Appending Files
This guide explains Python file I/O fundamentals, covering encoding, opening files with different modes, reading methods (read, readline, readlines), writing and flushing data, automatic closing with context managers, and practical examples such as word counting, all illustrated with clear code snippets.
File I/O in Python starts with understanding encoding (commonly UTF‑8) and the concept of files as persistent storage on disks.
Files are opened using open(name, mode, encoding='UTF-8') , where mode can be 'r' (read), 'w' (write), 'a' (append), etc. If the file does not exist, 'r' raises an error while 'w' and 'a' create a new file.
Reading methods include:
f.read(num) – reads up to num bytes or the whole file if omitted.
f.readline() – reads a single line and returns it as a string (including the newline character).
f.readlines() – returns a list of all lines, each ending with a newline.
Example:
f = open('python.txt', 'r', encoding='UTF-8')
print(f.read(10)) # reads first 10 bytes
line1 = f.readline()
print(line1, type(line1))
lines = f.readlines()
print(lines, type(lines))
f.close()Writing uses f.write('content') (buffered until f.flush() or f.close() ). The 'w' mode overwrites existing content, while 'a' appends to the end of the file.
Example of writing and flushing:
f = open('test.txt', 'w', encoding='UTF-8')
f.write('Your name')
f.flush()
f.close()Using a context manager automatically closes the file:
with open('python.txt', 'r', encoding='UTF-8') as f:
for line in f:
print(line, end='')A practical word‑count example demonstrates reading, splitting, and aggregating data:
with open('python.txt', 'r', encoding='UTF-8') as f:
words = []
for line in f:
line = line.strip()
words.extend(line.split(' '))
print(words)
print(words.count('itheima'))These snippets illustrate the essential operations for handling files in Python, suitable for beginners and anyone needing a concise reference.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.