Python实现经纬度转UTM数据及CSV转换报错排查
Hey there! Let's break down this IndexError you're hitting—this is a super common issue when working with CSV files, especially as a new Python dev, so don't worry, we'll fix it quickly.
What's causing the error?
The line company = eachline[0] throws IndexError: list index out of range because eachline is an empty list (or has fewer than 1 element) when your code tries to access index 0. That means, for at least one line in your input CSV, splitting it by | gives you nothing back (or not enough elements to work with).
Common reasons this happens:
- Empty lines in your CSV: If there's a blank line (maybe at the end of the file, or somewhere in the middle), stripping whitespace from it leaves an empty string, and splitting that results in an empty list.
- Malformed lines: Some line doesn't follow the
[name | lat | long]format—maybe it's missing a|, has extra spaces, or is just plain invalid. - Forgot to skip headers: If your CSV has a header row (like
name | lat | long), processing it like a data row might lead to unexpected splits (though this usually won't makeeachlineempty, it's still worth checking).
How to fix & debug this:
Let's modify your code to catch these issues and give you clear feedback. Here's a step-by-step adjustment tailored to your use case:
# Import your UTM conversion library (e.g., the `utm` package) import utm with open('your_input_file.csv', 'r') as input_file, open('output_utm.csv', 'w') as output_file: # Write your output CSV header if needed output_file.write("name | easting | northing | zone | --\n") # Track line numbers to identify problematic rows for line_num, line in enumerate(input_file, 1): # Strip leading/trailing whitespace from the entire line cleaned_line = line.strip() # Skip empty lines immediately if not cleaned_line: print(f"Skipping empty line at line {line_num}") continue # Split by |, then clean whitespace from each individual field eachline = [field.strip() for field in cleaned_line.split('|')] # Validate we have at least 3 required fields if len(eachline) < 3: print(f"Warning: Line {line_num} is malformed. Content: '{cleaned_line}'") print(f"Split into: {eachline} (needs at least 3 fields: name, lat, long)") continue # Safely access fields now that we know they exist company = eachline[0] lat_str = eachline[1] long_str = eachline[2] # Convert lat/long to numeric values (critical for UTM conversion) try: lat = float(lat_str) lon = float(long_str) except ValueError: print(f"Warning: Line {line_num} has invalid lat/long values: {lat_str}, {long_str}") continue # Perform UTM conversion easting, northing, zone_number, zone_letter = utm.from_latlon(lat, lon) # Write the formatted output line output_line = f"{company} | {easting} | {northing} | {zone_number}{zone_letter} | --\n" output_file.write(output_line) print("Conversion complete! Check the output file and console warnings for any issues.")
Key tips for your workflow:
- The list comprehension
[field.strip() for field in cleaned_line.split('|')]handles the spaces around|in your input format, so you don't end up with extra whitespace in your values. - The
try/exceptblock catches cases where lat/long aren't valid numbers (another easy-to-miss gotcha!). - The print statements will point you directly to problematic lines in your CSV, so you can fix them manually if needed.
Since your previous address-to-latlong code worked, the main difference here is likely that your new CSV has messy lines (empty or malformed) that your old dataset didn't have. This adjusted code will handle those gracefully instead of crashing.
内容的提问来源于stack exchange,提问作者James Briggs

