为了练习,我在书中写了这段代码。然而,当我尝试运行它时,它没有起作用,我一直有同样的错误";应为str、字节或os。PathLike对象,而不是读取器";。如果你们能检查一下并告诉我出了什么问题,那将是一件非常友好的事情。我很感激。提前谢谢!
import csv
ruta = open(r"C:UsersronaldDocumentsPYTHON DATAimportes.csv")
ruta = csv.reader(ruta)
with open(ruta, encoding='latin1') as fichero_csv:
lector = csv.reader(fichero_csv)
next(lector, None)
importe_total = 0
for linea in lector:
importe_str = linea [2]
importe = float(importe_str)
importe_total = importe_total + importe
print(importe_total)
您不需要调用open()
两次。只需在with
语句中以文件名为参数调用一次即可。
with open(r"C:UsersronaldDocumentsPYTHON DATAimportes.csv", encoding='latin1') as fichero_csv:
lector = csv.reader(fichero_csv)
next(lector, None)
importe_total = 0
for linea in lector:
importe_str = linea [2]
importe = float(importe_str)
importe_total = importe_total + importe
print(importe_total)