如何移除CSV文件第2列每行分隔符(.)后的内容?附代码求助
Hey there! Let's get your CSV processing sorted out. I see where you might have hit snags—let's break this down and get a working solution.
First, Fix the Column Index Issue
CSV rows in Python's csv module are zero-indexed. If you're targeting the second column (labeled "Time"), that's actually row[1], not row[2] (that would be the third column). That's probably why your earlier row[2][:-4] wasn't working as expected.
The Correct Processing Logic
For each time value:
- Check if it contains a
.(the millisecond separator) - If yes, split the string at the
.and keep the first part - If no, leave the value as-is
Full Working Code
We'll use with statements to handle file opening/closing safely (no need to manually call close()), and write the modified rows to a new CSV file:
import csv # Open original CSV and create new output CSV with open('Book1.csv', 'r') as input_file, open('Book1_no_ms.csv', 'w', newline='') as output_file: reader = csv.reader(input_file) writer = csv.writer(output_file) for row in reader: # Copy the row to avoid modifying original data modified_row = row.copy() # Target the second column (index 1) time_value = modified_row[1] # Remove milliseconds if present if '.' in time_value: modified_row[1] = time_value.split('.')[0] # Write the row to the new file writer.writerow(modified_row)
Why This Works
withstatements ensure files are properly closed even if an error occursrow.copy()prevents accidental changes to the original row datasplit('.')[0]cleanly grabs everything before the millisecond separator—this works reliably even if the millisecond portion has more/less than one digit- Rows without milliseconds stay untouched, exactly as you wanted
Example Output
If your original row looks like:["UserA", "14:38:01.1", "Login"]
It will become:["UserA", "14:38:01", "Login"]
A row without milliseconds like:["UserB", "09:15:00", "Logout"]
Stays unchanged.
内容的提问来源于stack exchange,提问作者Noegaard

