You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:如何根据行列值从CSV获取特定单元格值

Hey there! Since you're new to Python, let's walk through how to pull Mike's review from that CSV file. It's totally doable with Python's built-in tools—no fancy libraries needed!

Solution for Getting Mike's Review from CSV

The easiest way for beginners is to use Python's built-in csv module. It handles all the CSV formatting details (like quoted text) for you, and lets you access data by column names which is way more intuitive than counting columns.

Step-by-Step Code (Reading from a CSV File)

First, save your sample data into a file named hotels.csv. Then use this code:

import csv

# Open the CSV file safely using a 'with' block (it auto-closes the file for you)
with open('hotels.csv', mode='r') as csv_file:
    # Create a DictReader object—this turns each row into a dictionary with column headers as keys
    csv_reader = csv.DictReader(csv_file)
    
    # Loop through every row in the CSV
    for row in csv_reader:
        # Check if the 'user' column matches 'mike'
        if row['user'].lower() == 'mike':  # Using .lower() to avoid case sensitivity (e.g., 'Mike' would also work)
            # Print out Mike's review
            print("Mike's Review:", row['review'])

What This Code Does:

  • csv.DictReader: Converts each row into a dictionary where you can use column names (like row['user'] or row['review']) to access values—no need to remember which column index is which!
  • with open(...): This is the safest way to handle files in Python. It automatically closes the file once we're done, so you don't have to worry about forgetting csv_file.close().
  • The loop checks each row's user value, and when it finds 'mike', it grabs the corresponding review value and prints it.

Bonus: Test with Sample Data Directly (No File Needed)

If you don't want to save the CSV to a file and just want to test with your sample data, you can use StringIO to treat the CSV string as a file:

import csv
from io import StringIO

# Your sample CSV content as a string
sample_csv = """user,hotel_name,city,review
adam,hotel1,chennai,"Wow, what charm! As a Travel Agent."
john,hotel2,pune,Great location for sporting events.
mike,hotel3,mumbai,Its the best of the best.
george,hotel4,delhi,Ok hotel in a bad location."""

# Use StringIO to simulate a file
with StringIO(sample_csv) as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        if row['user'] == 'mike':
            print("Mike's Review:", row['review'])

When you run either of these codes, you'll get the output:

Mike's Review: Its the best of the best.

内容的提问来源于stack exchange,提问作者avi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:48:46