使用Python 3替换csv文件中的行

问题描述 投票:0回答:1

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

我有一个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 Operation 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-3233 Vera 5.5092操作65-2045 Sydney 3.4542 Executive 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.x csv overwrite
1个回答
0
投票

你可以

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

生成舍入值列表。

© www.soinside.com 2019 - 2024. All rights reserved.