使用open与csv.reader处理CSV文件的条件追加问题求助
Hey there! Let's break down how to solve both of your CSV handling needs cleanly and efficiently.
1. Better Way to Skip the First Two Rows
Your current approach of calling next(reader) twice works perfectly fine for two rows, but if you ever need to skip more rows later (or just want a more scalable/readable method), using itertools.islice is a great alternative. It lets you slice the reader iterator directly to skip the first N rows in one line:
import csv from itertools import islice with open('gios-pjp-data.csv', 'r') as data: l = [] reader = csv.reader(data, delimiter=';') # Skip first 2 rows (start iterating from index 2 onwards) reader = islice(reader, 2, None) # Rest of your processing code goes here
This is way cleaner than chaining multiple next() calls, especially if you end up needing to skip 5+ rows down the line.
2. Filter and Append Floats Greater Than 200
For your core requirement—extracting the first and third floating-point values (columns 2 and 4 in your CSV, which map to indexes 1 and 3 in zero-based counting) only when they're over 200—here's a straightforward implementation:
import csv from itertools import islice with open('gios-pjp-data.csv', 'r') as data: l = [] reader = csv.reader(data, delimiter=';') # Skip the first two header rows reader = islice(reader, 2, None) for row in reader: # Convert the relevant columns to float values first_float = float(row[1]) third_float = float(row[3]) # Append each value to the list only if it meets the >200 condition if first_float > 200: l.append(first_float) if third_float > 200: l.append(third_float)
Quick Notes:
- We use zero-based indexing here:
row[0]is the date string,row[1]is your first float,row[2]the second, androw[3]the third. - If you want to append both values as a pair (like a tuple
(first_float, third_float)) instead of individual entries, just adjust the logic—for example, append the tuple if either value is over 200, or only if both are, depending on your exact needs. - To handle edge cases (like rows with invalid non-float values), add a
try-exceptblock to avoid crashes:try: first_float = float(row[1]) third_float = float(row[3]) except ValueError: # Skip this row or log an error message continue
内容的提问来源于stack exchange,提问作者Piotrek Wcisło

