Python File Processing: CSV, Excel, Word and PDF

1. File path and basic operations

Python It is recommended to use pathlib to manage file paths.

from pathlib import Path

path = Path("data/report.csv")

path.exists()       # Does the file exist?
path.is_file()      # Is it a file
path.suffix         # ".csv"
path.stem           # "report"
path.name           # "report.csv"
path.parent         # Path("data")

Traverse files

folder = Path("data")

for path in folder.glob("*.csv"):
    print(path.name)

# Recursive search
for path in folder.rglob("*.pdf"):
    print(path)

Read and write text

path = Path("example.txt")

path.write_text("Hello World", encoding="utf-8")

content = path.read_text(encoding="utf-8")

binary file

data = Path("image.png").read_bytes()

Path("image_copy.png").write_bytes(data)

Copy, move and delete

import shutil

shutil.copy2("source.txt", "backup.txt")
shutil.move("backup.txt", "archive.txt")

Path("archive.txt").unlink()

When dealing with large numbers of files, attention should be paid to path existence, encoding, file coverage, and exception handling.

2. CSV file processing

CSV (Comma-Separated Values) is a text table format that does not contain the format, formulas, or multiple worksheets of Excel.

csv: standard library

Python comes with csv, no installation required.

Read CSV:

import csv

with open("data.csv", "r", encoding="utf-8-sig", newline="") as f:
    reader = csv.DictReader(f)

    for row in reader:
        print(row["name"], row["age"])

DictReader converts each row into a dictionary with field names from the CSV header.

Write CSV:

import csv

rows = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
]

with open("output.csv", "w", encoding="utf-8-sig", newline="") as f:
    writer = csv.DictWriter(
        f,
        fieldnames=["name", "age"],
    )

    writer.writeheader()
    writer.writerows(rows)

utf-8-sig can improve the encoding compatibility of Chinese CSV in some Excel environments.

Note: The field values read out by csv are all strings by default and need to be converted into numbers, dates and other types by yourself.

pandas: Table data processing

If data cleaning, filtering, and aggregation are required, Pandas is preferred.

import pandas as pd

df = pd.read_csv("data.csv")

df.head()
df.info()

df = df[df["age"] >= 18]

df.to_csv("output.csv", index=False)

Reading large files in chunks:

for chunk in pd.read_csv("large.csv", chunksize=100_000):
    print(chunk.shape)

selection principle: Use csv for simple line-by-line reading and writing, and use pandas when analysis and conversion are required.

3. Excel file processing

Excel common format:

  • .xlsx: Modern Excel workbook.
  • .xls: Legacy Excel format.
  • .xlsm: The macro-enabled Excel workbook.

Commonly used libraries:

  • openpyxl: Manipulate worksheets, cells, and styles in .xlsx files.
  • pandas: Read and analyze Excel as table data.

openpyxl

Installation:

pip install openpyxl

Read Excel:

from openpyxl import load_workbook

wb = load_workbook("data.xlsx")

print(wb.sheetnames)

ws = wb["Sheet1"]

print(ws["A1"].value)
print(ws.cell(row=2, column=1).value)

Iterate over rows:

for row in ws.iter_rows(
    min_row=2,
    values_only=True,
):
    print(row)

values_only=True returns the cell's value, not the Cell object.

Create and modify Excel

from openpyxl import Workbook

wb = Workbook()
ws = wb.active
ws.title = "Sales"

ws.append(["Product", "Revenue"])
ws.append(["A", 1000])
ws.append(["B", 1500])

ws["B4"] = "=SUM(B2:B3)"

wb.save("report.xlsx")

Style settings

from openpyxl.styles import Font, PatternFill, Alignment

ws["A1"].font = Font(bold=True)

ws["A1"].fill = PatternFill(
    fill_type="solid",
    fgColor="DDEEFF",
)

ws["A1"].alignment = Alignment(
    horizontal="center",
)

You can also control column width:

ws.column_dimensions["A"].width = 20

Note: openpyxl can write formulas, but the formula results will not be calculated like Excel.

pandas read and write Excel

import pandas as pd

df = pd.read_excel(
    "data.xlsx",
    sheet_name="Sheet1",
)

df.to_excel(
    "output.xlsx",
    sheet_name="Result",
    index=False,
)

Write to multiple worksheets:

with pd.ExcelWriter("report.xlsx") as writer:
    df1.to_excel(writer, sheet_name="Users", index=False)
    df2.to_excel(writer, sheet_name="Orders", index=False)

selection principle:

  • Just extract, clean, and analyze the Excel data: pandas.
  • Need to modify cells, set styles, formulas and worksheet structure: openpyxl.

4. Word file processing

Python often uses python-docx to process .docx files.

Installation:

pip install python-docx

Read Word

from docx import Document

doc = Document("document.docx")

for paragraph in doc.paragraphs:
    print(paragraph.text)

Read the table:

for table in doc.tables:
    for row in table.rows:
        values = [cell.text for cell in row.cells]
        print(values)

Note: doc.paragraphs and doc.tables return paragraphs and tables respectively, and cannot directly restore the original interleaved order of all elements in the document.

Create Word

from docx import Document

doc = Document()

doc.add_heading("Data Analysis Report", level=1)

doc.add_paragraph("This report summarizes the results.")

doc.add_heading("Results", level=2)

doc.add_paragraph("Revenue increased by 10%.")

doc.save("report.docx")

Set text style

from docx.shared import Pt

paragraph = doc.add_paragraph()

run = paragraph.add_run("Important Result")

run.bold = True
run.font.size = Pt(14)

Add table

table = doc.add_table(rows=1, cols=2)

table.rows[0].cells[0].text = "Product"
table.rows[0].cells[1].text = "Sales"

row = table.add_row()
row.cells[0].text = "A"
row.cells[1].text = "1000"

add picture

from docx.shared import Inches

doc.add_picture("chart.png", width=Inches(5))

doc.save("report.docx")

Common uses:

  • Automatically generate analysis reports.
  • Fill out documents in bulk.
  • Extract text and tables from Word.
  • Insert the Matplotlib chart into Word.

python-docx mainly handles the DOCX document structure and is not responsible for rendering Word into PDF, nor does it directly support older .doc files.

5. PDF file processing

The difference between PDF and Word is that PDF emphasizes fixed page layout rather than editable document structure.

Commonly used libraries:

LibraryMain purpose
pypdfMerge, split, rotate, extract text
PyMuPDFExtract text, get coordinates, images and page rendering
pdfplumberExtract text and tables with a certain structure
reportlabGenerate PDF from scratch

pypdf: Read text

Installation:

pip install pypdf
from pypdf import PdfReader

reader = PdfReader("document.pdf")

print(len(reader.pages))

for page in reader.pages:
    text = page.extract_text()
    print(text)

Merge PDF

from pypdf import PdfWriter

writer = PdfWriter()

writer.append("file1.pdf")
writer.append("file2.pdf")

with open("merged.pdf", "wb") as f:
    writer.write(f)

Extract specified page

from pypdf import PdfReader, PdfWriter

reader = PdfReader("document.pdf")
writer = PdfWriter()

writer.add_page(reader.pages[0])
writer.add_page(reader.pages[1])

with open("first_two_pages.pdf", "wb") as f:
    writer.write(f)

PyMuPDF: Text and page processing

Installation:

pip install pymupdf

Read text:

import pymupdf

with pymupdf.open("document.pdf") as doc:
    for page in doc:
        text = page.get_text()
        print(text)

Extract blocks of text:

with pymupdf.open("document.pdf") as doc:
    page = doc[0]
    blocks = page.get_text("blocks")

Render the PDF page as an image:

with pymupdf.open("document.pdf") as doc:
    page = doc[0]

    pix = page.get_pixmap(dpi=150)
    pix.save("page.png")

PDF table extraction

For PDF that contains a recognizable table structure, try:

import pdfplumber

with pdfplumber.open("report.pdf") as pdf:
    page = pdf.pages[0]

    tables = page.extract_tables()

    for table in tables:
        print(table)

PDF The accuracy of table extraction depends on the document layout, and complex spreads, merged cells, and borderless tables may not be restored accurately.

Scanned version PDF

Need to distinguish:

  • Text-based PDF: Contains real text objects and can be extracted directly.
  • Scanned PDF: Mainly composed of scanned pictures, usually OCR is required to recognize text.

pypdf and normal text extraction operations do not automatically recognize text in scanned images.

6. Batch file processing

In actual development, it is often necessary to process files in the entire directory.

For example, merge all CSV files:

from pathlib import Path
import pandas as pd

files = sorted(Path("data").glob("*.csv"))

if files:
    frames = [pd.read_csv(file) for file in files]

    combined = pd.concat(
        frames,
        ignore_index=True,
    )

    combined.to_csv("combined.csv", index=False)

Batch read Excel:

from pathlib import Path
import pandas as pd

for file in Path("reports").glob("*.xlsx"):
    df = pd.read_excel(file)

    print(file.name, len(df))

For large numbers of files, you should consider:

  • The file may be corrupted or formatted inconsistently.
  • Column names may differ from file to file.
  • A single file may exceed available memory.
  • Documentation of successful and failed processing is required.
  • Do not accidentally overwrite the source file with the output file.

7. How to choose common libraries

demandRecommended library
File path, traversal, copypathlib、shutil
Simple CSV read and writecsv
CSV/Excel Data Analysispandas
Excel cells, styles, worksheetsopenpyxl
Word document generation and modificationpython-docx
PDF merge, splitpypdf
PDF Text, page and image processingPyMuPDF
PDF table extractionpdfplumber
Generate PDF from scratchreportlab

Summary

The most worthy combinations for daily file processing:

Python File Processing
├── pathlib / shutil
│   └── File paths and file management
│
├── CSV / Excel
│   ├── csv
│   ├── pandas
│   └── openpyxl
│
├── Word
│   └── python-docx
│
└── PDF
    ├── pypdf
    ├── PyMuPDF
    └── pdfplumber

Core principles:

  1. For structured data, Pandas is preferred, especially CSV and Excel for data cleaning, statistics and conversion.
  2. Use openpyxlwhen needs to control the Excel workbook structure.
  3. Word uses python-docx, suitable for automatically generating and modifying DOCX reports.
  4. PDF Select the library according to the task: use pypdf for merging and splitting, and PyMuPDF for text and page processing.
  5. PDF does not equal for editable documents, complex document parsing and scanning of files may require specialized layout analysis or OCR.

Reference documentation

Back to top