如何用Python从CSV文件中提取两列数据到两个列表?
Hey there! Let's work through why you're hitting errors when trying to pull two columns from your CSV into separate lists. First, let's break down the issue with your current code and fix it step by step.
What's Wrong with Your Current Code?
Your existing code uses delimiter=' ' and quotechar='|', which is only correct if your CSV file uses spaces as separators and | as quote characters. Most standard CSVs use commas as delimiters, so this mismatch is likely causing parsing errors that prevent you from accessing specific columns.
Solution 1: Using csv.reader (For Index-Based Extraction)
This works great if you know the exact positions of the columns you want (remember, Python uses 0-based indexing):
import csv # Initialize empty lists to store your two columns column_1 = [] column_2 = [] with open('test-data.csv', newline='') as csvfile: # Update delimiter to match your CSV (comma is standard; use '\t' for tab-separated) csv_reader = csv.reader(csvfile, delimiter=',') # Skip the header row if your CSV has one (remove this line if there's no header) next(csv_reader) for row in csv_reader: # Make sure the row has at least 2 columns to avoid index errors if len(row) >= 2: column_1.append(row[0]) # First column (index 0) column_2.append(row[1]) # Second column (index 1) else: print(f"Skipping incomplete row: {row}") # Verify the results print("Column 1 data:", column_1) print("Column 2 data:", column_2)
Solution 2: Using csv.DictReader (For Header-Based Extraction)
If your CSV has a header row (e.g., first line has column names like Name, Age), this method is more readable because you can reference columns by their names instead of indexes:
import csv column_1 = [] column_2 = [] with open('test-data.csv', newline='') as csvfile: # DictReader uses the first row as column headers csv_reader = csv.DictReader(csvfile, delimiter=',') for row in csv_reader: # Replace 'FirstColumnName' and 'SecondColumnName' with your actual header names column_1.append(row['FirstColumnName']) column_2.append(row['SecondColumnName']) print("Column 1 data:", column_1) print("Column 2 data:", column_2)
Common Error Fixes
- IndexError: This happens if a row has fewer columns than you're trying to access. Always add a check like
len(row) >= 2to skip malformed rows. - Incorrect Delimiter: If your CSV uses tabs, semicolons, or another separator, update
delimiterto match (e.g.,delimiter=';'for semicolon-separated files). - File Not Found: Ensure
test-data.csvis in the same folder as your script, or use the full file path (e.g.,C:/Users/YourName/Documents/test-data.csvon Windows).
If you still get specific error messages, feel free to share them along with a sample line from your CSV, and we can refine this further!
内容的提问来源于stack exchange,提问作者L K

