杰瑞科技汇

Python如何正确导入cvs模块?

Of course! It looks like you meant to ask about importing CSV files in Python. The correct module name is csv (all lowercase).

The csv module is a built-in Python library, so you don't need to install it separately. It's designed to make reading from and writing to CSV (Comma-Separated Values) files easy.

Here’s a complete guide covering the most common tasks.


Reading a CSV File

This is the most common use case. Let's start with a sample CSV file named users.csv:

users.csv

name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago

Method 1: Using csv.reader (The Basic Way)

The csv.reader function reads the file row by row, where each row is a list of strings.

import csv
# Use 'with open' for safe file handling (automatically closes the file)
with open('users.csv', mode='r') as file:
    # csv.reader returns an object that iterates over lines in the CSV file
    csv_reader = csv.reader(file)
    # The first row is usually the header
    header = next(csv_reader)
    print(f"Header: {header}")
    # Loop through the remaining rows
    for row in csv_reader:
        # Each row is a list
        print(f"Name: {row[0]}, Age: {row[1]}, City: {row[2]}")

Output:

Header: ['name', 'age', 'city']
Name: Alice, Age: 30, City: New York
Name: Bob, Age: 25, City: Los Angeles
Name: Charlie, Age: 35, City: Chicago

Method 2: Using csv.DictReader (The Recommended Way)

This is often more intuitive because it maps each row to a dictionary, using the first row of the file as keys. This makes your code more readable and less prone to errors if the column order changes.

import csv
with open('users.csv', mode='r') as file:
    # csv.DictReader uses the first row of the file as keys for the dictionaries
    csv_reader = csv.DictReader(file)
    # No need to call next() to get the header, it's handled automatically
    # The fieldnames attribute contains the headers
    print(f"Headers: {csv_reader.fieldnames}")
    for row in csv_reader:
        # Each row is now an OrderedDict (a dictionary-like object)
        # You can access data by column name
        print(f"Name: {row['name']}, Age: {row['age']}, City: {row['city']}")

Output:

Headers: ['name', 'age', 'city']
Name: Alice, Age: 30, City: New York
Name: Bob, Age: 25, City: Los Angeles
Name: Charlie, Age: 35, City: Chicago

Writing to a CSV File

Writing is just as straightforward. Let's create a new file called new_users.csv.

Method 1: Using csv.writer

You provide a list for each row you want to write.

import csv
# The 'w' mode will create the file if it doesn't exist, or overwrite it if it does.
with open('new_users.csv', mode='w', newline='') as file:
    # Create a writer object
    csv_writer = csv.writer(file)
    # Write the header row
    csv_writer.writerow(['name', 'email', 'status'])
    # Write data rows
    csv_writer.writerow(['David', 'david@example.com', 'active'])
    csv_writer.writerow(['Eve', 'eve@example.com', 'inactive'])

After running this, a file named new_users.csv will be created with the following content:

name,email,status
David,david@example.com,active
Eve,eve@example.com,inactive

Note: newline='' is important. It prevents csv.writer from adding extra blank rows between your data on some operating systems (like Windows).

Method 2: Using csv.DictWriter

This is the preferred way to write data, as it allows you to specify the order of columns and automatically writes the header.

import csv
data_to_write = [
    {'name': 'Frank', 'email': 'frank@example.com', 'status': 'active'},
    {'name': 'Grace', 'email': 'grace@example.com', 'status': 'pending'}
]
with open('new_users_dict.csv', mode='w', newline='') as file:
    # Define the fieldnames (column headers)
    fieldnames = ['name', 'email', 'status']
    # Create a DictWriter object
    csv_writer = csv.DictWriter(file, fieldnames=fieldnames)
    # Write the header row
    csv_writer.writeheader()
    # Write the data rows
    csv_writer.writerows(data_to_write)

After running this, new_users_dict.csv will contain:

name,email,status
Frank,frank@example.com,active
Grace,grace@example.com,pending

Handling Different Delimiters (e.g., Semicolons)

Sometimes files use a delimiter other than a comma, like a semicolon () or a tab (\t). You can specify this using the delimiter argument.

Let's say you have a file data_semicolon.csv:

product_id;price;stock
P001;19.99;150
P002;25.50;80

You can read it like this:

import csv
with open('data_semicolon.csv', mode='r') as file:
    csv_reader = csv.reader(file, delimiter=';')
    for row in csv_reader:
        print(row)

Output:

['product_id', 'price', 'stock']
['P001', '19.99', '150']
['P002', '25.50', '80']

Summary: Which to Use?

Task Recommended Method Why?
Reading csv.DictReader Code is more readable, less error-prone, and self-documenting.
Writing csv.DictWriter You control column order, and it automatically writes the header.
Simple Reading csv.reader Good for very simple files where you just need a quick list of lists.
Simple Writing csv.writer Good for writing simple, sequential data without worrying about headers.

For most real-world applications, DictReader and DictWriter are your best friends.

分享:
扫描分享到社交APP
上一篇
下一篇