我正在尝试使用 pandas.csv_reader()创建一个熊猫数据框。我有要求在读取文件期间需要执行一些自定义逻辑。我知道熊猫可以带一个具有read()方法的对象。 我的代码看起来像这样
class Reader:
def read(self, n = 10):
ls = []
for i in range(n):
ls.append(self.readline()) # implemented in code
return '\n'.join(ls)
# creating dataframe like this
obj = Reader()
df = pd.read_csv(obj, header=None)
但是我遇到这样的错误
File "/lib/python3.6/site-packages/pandas/io/parsers.py", line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File "/lib/python3.6/site-packages/pandas/io/parsers.py", line 440, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "/lib/python3.6/site-packages/pandas/io/parsers.py", line 787, in __init__
self._make_engine(self.engine)
File "/lib/python3.6/site-packages/pandas/io/parsers.py", line 1014, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "/lib/python3.6/site-packages/pandas/io/parsers.py", line 1708, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas/_libs/parsers.pyx", line 539, in pandas._libs.parsers.TextReader.__cinit__
File "pandas/_libs/parsers.pyx", line 829, in pandas._libs.parsers.TextReader._get_header
File "pandas/_libs/parsers.pyx", line 932, in pandas._libs.parsers.TextReader._tokenize_rows
File "pandas/_libs/parsers.pyx", line 2098, in pandas._libs.parsers.raise_parser_error
ValueError: I/O operation on closed file.