You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除CSV文件第2列每行分隔符(.)后的内容?附代码求助

Fixing CSV Time Column Millisecond Removal

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

  • with statements ensure files are properly closed even if an error occurs
  • row.copy() prevents accidental changes to the original row data
  • split('.')[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:42:40