You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python CSVFile类读取异常:误将文件名当作文件内容

问题:CSVFile类read_file方法读取错误,将文件名字符逐行返回

问题现象

  • 自定义CSVFile类的write_line方法可正常将['a','b','c']写入文件,文件实际内容为a,b,c
  • 调用read_file方法传入文件名"test"时,返回结果为[['t'],['e'],['s'],['t']],错误地将文件名的每个字符当作一行读取,导致pytest断言失败

问题根源

read_file方法的实现逻辑错误,没有正确打开目标文件读取内容,反而直接遍历了文件名字符串,把文件名的每个字符当作独立行处理。

修复后的完整代码示例

import csv

class CSVFile:
    def __init__(self, filename):
        self.filename = filename

    def write_line(self, data):
        # 原write_line方法逻辑正确,保留
        with open(self.filename, 'w', newline='') as file:
            csv_writer = csv.writer(file)
            csv_writer.writerow(data)

    def read_file(self):
        # 修复核心:正确打开文件并使用csv.reader解析内容
        result_rows = []
        with open(self.filename, 'r', newline='') as file:
            csv_reader = csv.reader(file)
            for row in csv_reader:
                result_rows.append(row)
        return result_rows

验证结果

修复后调用read_file方法,会正确解析文件中的a,b,c内容,返回[['a', 'b', 'c']],与预期一致,pytest断言可通过。

内容的提问来源于stack exchange,提问作者Burvil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:10:30