类型错误:预期为str、bytes或os.PathLike对象,而不是reader

0 投票
1 回答
54 浏览
提问于 2025-04-13 18:11

我正在尝试读取很多csv文件,并搜索里面的“error”这个词。

使用csv.reader的时候遇到了一些问题,因为我觉得它在寻找一个字符串。

我不确定换成文本格式是否会有帮助?

import glob
import os # Imported os
import csv
import pathlib

def find_cell(csv_file, check):
    with open(csv_file,'r') as file:
        reader = csv.reader(file)
        for row_idx, row in enumerate(reader):
            for col_idx, cell in enumerate(row):
                if cell == check:
                    return row_idx, col_idx
    return None

def errorCheck(Filename):

    is_match = False

    with open(Filename) as f:
        csv_file = csv.reader(f, delimiter='|')
        check = 'Error'
        cell_location = find_cell(csv_file, check)
        if cell_location:
            row_idx, col_idx = cell_location
            print("ERROR")
            print_and_log('ERROR IN FILE - '+ Filename + 'row '+ {row_idx} +'column ' + {col_idx})
            is_match = True
    if is_match:
        return

1 个回答

1

open() 函数可以接受字符串、字节或者路径类型的对象。如果你像之前那样用 csv.reader() 来调用 open(),就会出现错误。

建议你直接把 Filename 传给 find_cell(),而不是先去读取文件,因为 find_cell() 本身会进行读取操作。

def errorCheck(Filename):
    is_match = False
    check = 'Error'
    cell_location = find_cell(Filename, check)
    if cell_location:
        row_idx, col_idx = cell_location
        print("ERROR")
        print_and_log('ERROR IN FILE - '+ Filename + 'row '+ {row_idx} +'column ' + {col_idx})
        is_match = True
    if is_match:
        return

我做了什么?我去掉了文件上下文,因为其实不需要,因为 find_cell() 最终会自己去 open() 文件。

撰写回答