Python读取DBC文件用for循环仍仅获首行的问题求助
Hey there! I see you're stuck with reading your car.dbc file—let's break down what's going wrong and fix it together.
The Root Cause
Look at your function definition: the return lines statement is inside the for loop. That means as soon as the loop runs once (processing the first line of the file), the function immediately sends back the result and stops executing. All the other lines in your file never get touched!
On top of that, you're overwriting the lines variable every loop with lines = row.split(' ')—even if the return was in the right place, you'd only end up with the last line's split values, not all rows.
Fixed Code
Here's the corrected version, with explanations:
def function(f): lines = [] for Nrow, row in enumerate(f): # First, strip whitespace/newlines from the start/end of the line cleaned_row = row.strip() # Skip empty lines (in case your file has any) if not cleaned_row: continue # Split the line into parts, then filter out empty strings (from extra spaces) split_parts = cleaned_row.split(' ') split_parts = [part for part in split_parts if part] # Add the cleaned, split row to our list lines.append(split_parts) # Return the full list AFTER processing all lines return lines with open('car.dbc', 'r') as f: contents = function(f) print(contents) # Optional: Check how many rows were read to confirm print(f"Total rows read: {len(contents)}")
Key Improvements
- Moved
return linesoutside the for loop so the function finishes processing every line before returning. - Used
lines.append()instead of overwriting the variable, so we collect all rows. - Added
strip()to remove unwanted newlines/whitespace, and filtered out empty strings from splits (common if your .dbc file has multiple spaces between values). - Added a check to skip empty lines, which keeps your output cleaner.
Bonus: Handling Special Lines in .dbc Files
If your car.dbc has comment lines (like ones starting with //) or other metadata you want to skip, you can add an extra condition:
for Nrow, row in enumerate(f): cleaned_row = row.strip() # Skip empty lines AND comment lines if not cleaned_row or cleaned_row.startswith('//'): continue # Rest of the processing...
Test this out, and you should see all lines from your .dbc file show up in the contents list!
内容的提问来源于stack exchange,提问作者Venkatesh Kaduru

