Python中的CSV导入和操作

时间:2018-08-16 05:46:09

标签: python-3.x csv

我是Python的新手,正在尝试获取包含以下内容的CSV文件:

Computers,price
comp1,150
comp2,250
comp3,100
comp4,175
comp5,60

我正在尝试读取此数据(使用导入CSV模块),然后我想删除价格低于125的任何计算机,然后要添加一个列为quality的列。 对于其余计算机,我想根据以下

将新列中的数据设置为高或平均
if price is <= 175 
    the price = average 
    else price = High

这是我到目前为止所拥有的:

#python 3.7

# Program to read input and out a new file with changes based on conditions

import csv

  with open('c:\computers.csv', 'r') as input, open('output.csv', 'wb') as 
      output:
      csv_input = csv.reader(input)
      csv_output = csv.writer(output, lineterminator='\n')

# keep only computers 125 or over

csv_output.writerow(next(csv_input))

for cols in csv_input:
  if float(cols[2]) <=125:
    csv_output.writerows(cols)

#Create new Column called Quality

headers = reader.next()
headers.append('Quality')
writer.writerow(headers)

# Check price and set Quality Column to Average if price <= 175 otherwise set to High

这是我到目前为止的位置。我想我需要做一个if if else,但不知道如何查找价格列,并且如果<= 175追加(我假设)作为平均质量列在质量列中,否则追加到质量列为High处。

再次,我是新手,所以我希望在这里不要被炸死。

感谢您的协助。

谢谢

1 个答案:

答案 0 :(得分:0)

我想你想要

for cols in csv_input:
  if float(cols[2]) >125:
    if float(cols[2]) >175:
      cols[3]='High'
    else:
      cols[3]='Average'
    csv_output.writerows(cols)

在此之前放置标题部分