Python Tutorial: Working with Excel, Word, and CSV Files Using xlrd/xlwt/xlutils, python-docx, and csv Modules
This comprehensive guide demonstrates how to read, write, modify, and format Excel, Word, and CSV files in Python using libraries such as xlrd/xlwt/xlutils for Excel, python-docx for Word, and the built‑in csv module, complete with code examples and feature comparison tables.
Python is widely used for data processing, and interacting with common office formats like Excel, Word, and CSV is essential. This article introduces the most popular libraries for each format and provides practical code snippets.
Excel Operations
For Excel handling, the xlrd , xlwt , xlutils , XlsxWriter , and OpenPyXL libraries are commonly used. The table below compares their capabilities:
Feature
xlrd&xlwt&xlutils
XlsxWriter
OpenPyXL
Excel COM Interface
Read
Supported
Not supported
Supported
Supported
Write
Supported
Supported
Supported
Supported
Modify
Supported
Not supported
Supported
Supported
xls format
Supported
Not supported
Not supported
Supported
xlsx format
High‑version only
Supported
Supported
Supported
Large files
Not supported
Supported
Supported
Not supported
Efficiency
Fast
Fast
Fast
Very slow
Functionality
Weak
Powerful
Average
Very powerful
Below are concise examples for writing, reading, and modifying Excel files using xlwt and xlrd together with xlutils :
<code># Install the libraries
$ pip install xlrd xlwt xlutils
# Write an .xls file
import xlwt
wb = xlwt.Workbook()
sh1 = wb.add_sheet('成绩')
sh1.write(0, 0, '姓名')
sh1.write(0, 1, '专业')
sh1.write(0, 2, '科目')
sh1.write(0, 3, '成绩')
# ... (additional rows) ...
wb.save('test.xls')
</code> <code># Read the .xls file
import xlrd
wb = xlrd.open_workbook('test.xls')
sh1 = wb.sheet_by_index(0)
print('Rows:', sh1.nrows, 'Cols:', sh1.ncols)
print('First row, second column:', sh1.cell_value(0, 1))
</code> <code># Modify using xlutils
import xlrd
from xlutils.copy import copy
rb = xlrd.open_workbook('test.xls')
wb = copy(rb)
sh = wb.get_sheet(0)
sh.write(4, 0, '王欢')
sh.write(4, 1, '通信工程')
sh.write(4, 2, '机器学习')
sh.write(4, 3, 89)
wb.save('test_modified.xls')
</code>Word Operations
The python-docx library (current version 0.8.10) enables creation and manipulation of Word documents. Installation is performed with pip install python-docx .
<code># Create a new document with a title
from docx import Document
doc = Document()
doc.add_heading('How to Create and Manipulate Word with Python', 0)
doc.save('example.docx')
</code>Further examples show how to add headings, paragraphs, styled text, lists, images, and tables, as well as how to read existing documents and iterate over paragraphs and tables.
<code># Add formatted text and a quote
paragraph = doc.add_paragraph('This is a paragraph.')
run = paragraph.add_run(' (font size 20)')
run.font.size = Pt(20)
run.bold = True
run.italic = True
run.underline = True
run.font.color.rgb = RGBColor(0xFF, 0x00, 0x00)
doc.add_paragraph('A quoted line.', style='Intense Quote')
</code>CSV Operations
Python’s built‑in csv module provides reader and writer classes, as well as DictReader and DictWriter for dictionary‑based I/O. It also offers the Sniffer class to detect dialects.
Key constants for quoting behavior:
Constant
Description
QUOTE_ALL
Quote all fields
QUOTE_MINIMAL
Quote only fields containing special characters
QUOTE_NONNUMERIC
Quote all non‑numeric fields
QUOTE_NONE
No quoting
<code># Write a CSV file
import csv
with open('test.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['id', 'name', 'age'])
data = [('1001', '张三', '21'), ('1002', '李四', '31')]
writer.writerows(data)
</code> <code># Read a CSV file
import csv
with open('test.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(', '.join(row))
</code> <code># Detect dialect automatically
import csv
with open('test.csv', newline='') as csvfile:
sample = csvfile.read(1024)
dialect = csv.Sniffer().sniff(sample)
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
for row in reader:
print(row)
</code>Finally, the article lists common file‑mode strings (e.g., 'r' , 'w' , 'a' , and their + variants) for reading, writing, and appending both text and binary files.
Overall, the guide equips readers with practical code snippets and comparative information to efficiently handle Excel, Word, and CSV files in Python projects.
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.