杰瑞科技汇

Python reader模块如何正确导入使用?

Of course! The term "Python reader import" can refer to a few different things, but most commonly it means importing the csv module to read data from a CSV file.

Python reader模块如何正确导入使用?-图1
(图片来源网络,侵删)

I'll cover the most important "readers" in Python, starting with the most frequent use case.


The csv Module: Reading CSV Files

This is the standard and most common way to read Comma Separated Values (CSV) files in Python. You first need to import csv.

Basic Example: Reading a CSV File

Let's say you have a file named users.csv with the following content:

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

Here's how you would read it using the csv module:

Python reader模块如何正确导入使用?-图2
(图片来源网络,侵删)
import csv
# Use a 'with' statement for safe file handling (it automatically closes the file)
with open('users.csv', mode='r', newline='', encoding='utf-8') as file:
    # csv.reader() returns a reader object that iterates over lines in the CSV file
    csv_reader = csv.reader(file)
    # The first row is often the header
    header = next(csv_reader)
    print(f"Header: {header}\n")
    # Loop through the remaining rows in the csv_reader object
    for row in csv_reader:
        # Each row is a list of strings
        print(f"Reading row: {row}")
        print(f"Name: {row[0]}, Age: {row[1]}, City: {row[2]}\n")

Output:

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

Reading CSV Files as Dictionaries (DictReader)

A more convenient way is to use csv.DictReader, which treats each row as an ordered dictionary, using the first row of the file as keys.

import csv
with open('users.csv', mode='r', newline='', encoding='utf-8') as file:
    # DictReader uses the first row of the file as keys for the dictionaries
    csv_dict_reader = csv.DictReader(file)
    print("--- Reading as Dictionaries ---")
    for row in csv_dict_reader:
        # You can access data using column names (keys)
        print(f"Name: {row['name']}, Age: {row['age']}, City: {row['city']}")

Output:

--- Reading as Dictionaries ---
Name: Alice, Age: 30, City: New York
Name: Bob, Age: 25, City: Los Angeles
Name: Charlie, Age: 35, City: Chicago

The json Module: Reading JSON Files

JSON (JavaScript Object Notation) is another extremely common format for storing and transporting data. You use the json module to read these files.

Python reader模块如何正确导入使用?-图3
(图片来源网络,侵删)

Let's say you have a file named data.json:

{
  "name": "Python",
  "version": 3.10,
  "is_fun": true,
  "features": ["Simple", "Readable", "Powerful"]
}

Here's how to read it:

import json
with open('data.json', mode='r', encoding='utf-8') as file:
    # json.load() parses the JSON file object and returns a Python dictionary
    data = json.load(file)
    # Now you can work with the data as a normal Python dictionary/list
    print(f"Name: {data['name']}")
    print(f"Version: {data['version']}")
    print(f"Is it fun? {data['is_fun']}")
    print(f"Features: {data['features'][0]}")

Output:

Name: Python
Version: 3.1
Is it fun? True
Features: Simple

Reading from Standard Input (sys.stdin)

Sometimes you want to write a script that can read data from a pipe or from user input, rather than a file. For this, you import the sys module and use sys.stdin.

This is common in command-line tools. For example, you could pipe the output of one command into your Python script.

import sys
print("--- Reading from Standard Input (press Ctrl+D or Ctrl+Z to end) ---")
for line in sys.stdin:
    # The 'line' variable will contain each line of input
    # It includes the newline character, so we strip it
    processed_line = line.strip()
    print(f"Received: {processed_line}")

How to run it:

  1. Save the code as read_stdin.py.
  2. In your terminal, you can type directly into it:
    python read_stdin.py
  3. Or, you can "pipe" another command's output into it:
    echo -e "hello\nworld\nfrom python" | python read_stdin.py

Output from the pipe example:

--- Reading from Standard Input (press Ctrl+D or Ctrl+Z to end) ---
Received: hello
Received: world
Received: from python

Reading from URLs (urllib or requests)

To read data directly from a web URL, you need a library that can handle HTTP requests. The standard library has urllib, but the more popular and user-friendly option is the requests library (which you may need to install first with pip install requests).

Using requests (Recommended)

import requests
# URL to read from (this URL provides sample user data)
url = "https://jsonplaceholder.typicode.com/users/1"
try:
    # Send a GET request to the URL
    response = requests.get(url)
    # Raise an exception if the request was unsuccessful (e.g., 404 Not Found)
    response.raise_for_status()
    # The content of the response is in JSON format, so we parse it
    user_data = response.json()
    print(f"User ID: {user_data['id']}")
    print(f"Name: {user_data['name']}")
    print(f"Email: {user_data['email']}")
except requests.exceptions.RequestException as e:
    print(f"Error fetching data from URL: {e}")

Output:

User ID: 1
Name: Leanne Graham
Email: Sincere@april.biz

Summary Table

Module/Library Use Case Key Function/Method Data Structure Read Into
csv Reading from/writing to CSV files. csv.reader(file) List of lists
json Reading from/writing to JSON files. json.load(file) Dictionary or List
sys Accessing system-specific parameters and functions. for line in sys.stdin: Reads line-by-line as strings
requests Making HTTP requests (the modern way). response = requests.get(url)
response.json()
Dictionary (after parsing JSON)

For most data reading tasks in Python, you will be using import csv or import json.

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