import csv with open("price.csv","r")as f,open("price_discount.csv","w",newline="")as g: reader=csv.reader(f) writer=csv.writer(g) for row in reader: price_discount=[float(price)*0.8 for pric in row[1:]] writer.writerow([row[0]+price_discount])这段代码有什么错误
时间: 2024-02-26 15:58:23 浏览: 143
csv_file.rar_csv_csv文件_python_python 读写 excel_python处理csv数据
5星 · 资源好评率100%
这段代码有一些错误:
1. 在 `import csv` 语句前缺少了换行符。
2. 在 `with open("price.csv","r")as f,open("price_discount.csv","w",newline="")as g:` 这行代码中,应该将 `as` 关键字放在 `open` 函数的括号后面。
3. 在 `price_discount=[float(price)*0.8 for pric in row[1:]]` 这行代码中,应该将 `pric` 改为 `price`。
4. 在 `writer.writerow([row[0]+price_discount])` 这行代码中,应该将 `price_discount` 改为 `*price_discount`,因为 `price_discount` 是一个列表,需要使用 `*` 运算符将其解包后再传递给 `writerow` 函数。
下面是修改后的代码:
```
import csv
with open("price.csv", "r") as f, open("price_discount.csv", "w", newline="") as g:
reader = csv.reader(f)
writer = csv.writer(g)
for row in reader:
price_discount = [float(price) * 0.8 for price in row[1:]]
writer.writerow([row[0], *price_discount])
```
阅读全文