首页 > 解决方案 > 使用 Python 3 替换 csv 文件中的一行

问题描述

我有一个问题的变体已经被问过,但我无法在我之前的所有帖子中找到我的特定问题的答案。所以我希望有人可以帮助我...

我有一个这样的 csv 文件(在这个例子中,总共有 18 行和 4 列,前 2 行包含标题)。

"Employees.csv" 17 ID 名称 值 位置 25-2002 James 1.2919 Finance 25-2017 Matthew 2.359 Legal 30-3444 Rob 3.1937 Operations 55-8988 Fred 3.1815 Research 26-1000 Lisa 4.3332 Research 56-0909 John 3.3533 Legal 45-8122 Anna 3.8887 财务 10-1000 Rachel 4.1448 维护 30-9000 Frank 3.7821 维护 25-3000 Angela 5.5854 服务 45-4321 Christopher 9.1598 法律 44-9821 Maddie 8.5823 服务 20-4000 Ruth 7.47 运营 50-32433 运营 50-3243 Vera 2050 5.50 悉尼45-8720 弗拉基米尔 0.2159 财务

我想将第 3 列中的值四舍五入到小数点后 2 位,即 round(value, 2)。所以基本上,我想打开文件,读取第 3 列(减去前 2 行),对每个值进行四舍五入,将它们写回,然后保存文件。在阅读了其他类似的帖子之后,我现在了解到最好总是创建一个临时文件来完成这项工作,而不是尝试一次更改同一个文件。所以我有以下代码:

import csv, os
val = []

with open('path/Employees.csv', 'r') as rf, open('path/tmpf.csv, 'w') as tmpf:
    reader = csv.reader(rf)
    writer = csv.writer(tmpf)
    for _ in range(2): #skip first 2 rows
        next(reader)
    for line in reader:
        val.append(float(line[2]))  # read 3 column into list 'val'

#    [... this is where i got stuck!  
#     ... how do I round each value of val, and
#     ... write everything back to the tmpf file ?]

os.remove('path/Employees.csv')
os.rename('path/tmpf', 'path/Employees.csv')

谢谢!

标签: python-3.xcsvoverwrite

解决方案


你可以

rounded_val = [ round (v,2) for v in val ]

生成四舍五入值列表。


推荐阅读