杰瑞科技汇

Python中如何用DictWriter写入CSV字典数据?

Of course! The csv.DictWriter class in Python's standard csv module is an excellent tool for writing data to a CSV file when your data is naturally structured as a list of dictionaries.

Python中如何用DictWriter写入CSV字典数据?-图1
(图片来源网络,侵删)

Each dictionary in your list represents a row, and the keys of the dictionary become the column headers.

Here's a complete guide, from a simple example to more advanced use cases.

The Basic Concept

  • Input: A list of dictionaries. Each dictionary must have the same set of keys.
  • Process: DictWriter takes this list and writes it to a file, automatically handling the headers and formatting the rows.
  • Output: A clean, well-formatted CSV file.

Simple Example: Writing to a New File

This is the most common use case. Let's create a CSV file named users.csv.

import csv
# 1. Your data: a list of dictionaries
users = [
    {'name': 'Alice', 'age': 30, 'city': 'New York'},
    {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
    {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]
# 2. The fieldnames (column headers) for the CSV file
# It's good practice to define this explicitly.
fieldnames = ['name', 'age', 'city']
# 3. The filename
filename = 'users.csv'
# 4. Writing to the CSV file
# The 'w' mode means write. If the file exists, it will be overwritten.
# newline='' is crucial to prevent blank rows from being written between each data row.
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
    # Create a DictWriter object
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    # Write the header row
    writer.writeheader()
    # Write the data rows
    writer.writerows(users)
print(f"File '{filename}' has been created successfully.")

What the users.csv file will look like:

Python中如何用DictWriter写入CSV字典数据?-图2
(图片来源网络,侵删)
name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago

Key Parameters and Methods

Let's break down the important parts of the code above.

The open() function

  • 'w': Write mode. This creates the file if it doesn't exist, or overwrites it if it does.
  • newline='': This is very important. Without it, you will get a blank line between every row in your CSV file on some operating systems (like Windows).
  • encoding='utf-8': A good practice to ensure your file can handle special characters (like accents, emojis, etc.) correctly.

The csv.DictWriter Constructor

  • csvfile: The file object returned by open().
  • fieldnames: A list of strings representing the column headers. DictWriter uses this to know the order and which keys to look for in your dictionaries.

The DictWriter Methods

  • writeheader(): This method writes the fieldnames as the first row in the CSV file.
  • writerows(rows): Takes a list of dictionaries and writes each one as a new row. This is the most efficient way to write all your data at once.
  • writerow(row): Takes a single dictionary and writes it as one row. Use this if you're writing data row by row in a loop.

Advanced Example: Appending to an Existing File

What if you want to add more data to your users.csv without deleting the old data? You can use append mode ('a').

import csv
# New users to add
new_users = [
    {'name': 'David', 'age': 40, 'city': 'Houston'},
    {'name': 'Eve', 'age': 28, 'city': 'Phoenix'}
]
# The fieldnames must match the existing file's headers
fieldnames = ['name', 'age', 'city']
filename = 'users.csv'
# Use 'a' for append mode
with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    # Note: You do NOT call writeheader() in append mode,
    # unless you want to add the header row again at the end of the file.
    writer.writerows(new_users)
print(f"New users have been appended to '{filename}'.")

The updated users.csv file will now be:

name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
David,40,Houston
Eve,28,Phoenix

Handling Different CSV Dialects (e.g., Excel)

Sometimes you need to create a CSV file that is compatible with a specific program like Microsoft Excel. You can specify a dialect for this.

Python中如何用DictWriter写入CSV字典数据?-图3
(图片来源网络,侵删)
import csv
data = [
    {'Product': 'Laptop', 'Price': 1200, 'In_Stock': 'Yes'},
    {'Product': 'Mouse', 'Price': 25, 'In_Stock': 'No'}
]
fieldnames = ['Product', 'Price', 'In_Stock']
filename = 'products_for_excel.csv'
# The 'excel' dialect is the default, but 'excel-tab' is useful for TSV files.
# You can also define custom dialects.
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
    # Use the 'excel' dialect, which ensures proper formatting for Excel
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect='excel')
    writer.writeheader()
    writer.writerows(data)
print(f"Excel-compatible file '{filename}' created.")

What if Dictionary Keys Don't Match fieldnames?

DictWriter is strict. If a dictionary is missing a key that's in fieldnames, it will raise a ValueError. If a dictionary has extra keys not in fieldnames, they will be ignored.

Example of a mismatch:

import csv
# A row is missing the 'age' key
users = [
    {'name': 'Frank', 'age': 50, 'city': 'Boston'},
    {'name': 'Grace'} # This will cause an error
]
fieldnames = ['name', 'age', 'city']
filename = 'error_example.csv'
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    try:
        writer.writerows(users)
    except ValueError as e:
        print(f"An error occurred: {e}")

Output:

An error occurred: dict missing keys: 'age'

Summary: When to Use csv.DictWriter

Use Case Best Tool Why
Your data is already in a list of dictionaries. csv.DictWriter Perfect fit. Minimal code, very readable.
Your data is in a list of lists (or tuples). csv.writer More direct and slightly faster for this structure.
You need maximum control over formatting (e.g., custom delimiters, quoting). csv.writer Offers lower-level control over each cell.
You need to read a CSV file into a list of dictionaries. csv.DictReader The counterpart to DictWriter.
分享:
扫描分享到社交APP
上一篇
下一篇