Python从CSV筛选指定列写入新文件:空文件问题及代码排查
Hey there! Let's break down the common issues that might be causing your output CSV to be empty, and how to properly assign those three columns to your result variable.
Common Mistakes & Fixes
1. You're not handling CSV data types correctly
CSV files read all values as strings by default—this is a super common pitfall! If you're trying to compare row[10] (wind speed) directly to a number, or check row[11] (fog) as a boolean without conversion, your filter conditions will never match, leaving result empty.
Fix this by explicitly converting values first:
import csv result = [] with open('input.csv', 'r') as f: reader = csv.reader(f) next(reader) # Skip header row if exists for row in reader: # Handle type conversion with error checking try: date = row[0] # Keep as string, or convert to datetime if needed wind_speed = float(row[10]) # Convert fog column to boolean (adjust based on your CSV's actual values: "True"/"False", 1/0, etc.) fog = row[11].strip().lower() == "true" or row[11] == "1" except (ValueError, IndexError): # Skip rows with invalid data (e.g., non-numeric wind speed) continue # Add your filter condition here (example: wind speed > 5 and fog is True) if wind_speed > 5 and fog: result.append([date, wind_speed, fog])
2. You're not properly populating the result variable
If you're maintaining separate lists for dates, wind speeds, and fog values, you need to combine them into a single list of rows for result. For example:
# If you have three separate lists: dates = [] wind_speeds = [] fogs = [] # ... (populate these lists with valid data) # Combine them into result: result = list(zip(dates, wind_speeds, fogs))
⚠️ Note: If the three lists are different lengths, zip will truncate to the shortest one—make sure you're adding values to all three lists only when the row meets your conditions.
3. Your write-to-CSV logic is flawed
Even if result has data, you might be writing it incorrectly. Make sure you're using writerows() (plural) to write all rows at once, or looping through result with writerow():
with open('output.csv', 'w', newline='') as f: writer = csv.writer(f) # Write header first (optional but recommended) writer.writerow(["Date", "Wind Speed", "Fog"]) # Write all filtered rows writer.writerows(result)
4. Your filter condition is too strict or logically inverted
Double-check your condition logic—for example, if you meant to keep rows where wind speed is less than 5 but wrote wind_speed > 5, no rows will match. Test with a small sample of your CSV to verify the condition works as expected.
Quick Summary
- Always convert CSV string values to their correct data types before filtering
- Ensure your filter conditions align with your actual requirements
- Populate
resultwith rows (each row is a list of the three columns) that meet your criteria - Use proper CSV writing methods to output the
resultdata
内容的提问来源于stack exchange,提问作者Ghgh Lhlh

