Home > database >  expected str, bytes or os.PathLike object, not reader
expected str, bytes or os.PathLike object, not reader

Time:10-31

I wrote this code from a book in order to practise. However, when I tried to run it, it didn't work and I keep having the same error "expected str, bytes or os.PathLike object, not reader". It would be nice and friendly if you guys could check it out and tell me, what went wrong. I'd appreciate it. Thanks in advance!

import csv
ruta = open(r"C:\Users\ronald\Documents\PYTHON DATA\importes.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)

CodePudding user response:

You don't need to call open() twice. Just call it once, with the filename as the argument, in the with statement.

with open(r"C:\Users\ronald\Documents\PYTHON DATA\importes.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)
  • Related