python - 使用 python-requests 保存 csv 文件时,有人可以帮助解决 Pandas 错误吗?
问题描述
有人可以帮我理解为什么这段代码会引发错误,并提供一个解决方案,我可以如何将我的文件保存在我的本地机器上:
myLast = result[:1]
for x in myLast:
urldailyLocal= os.path.basename(x)
s=requests.get(x, verify=False).content
c=pd.read_csv(s)
c.to_csv('path/to/my/file/'+urldailyLocal, index=False)
运行上述代码后报错:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/usr/local/lib/python3.7/site-packages/pandas/io/parsers.py", line 676, in parser_f
return _read(filepath_or_buffer, kwds)
File "/usr/local/lib/python3.7/site-packages/pandas/io/parsers.py", line 448, in _read
parser = TextFileReader(fp_or_buf, **kwds)
File "/usr/local/lib/python3.7/site-packages/pandas/io/parsers.py", line 880, in __init__
self._make_engine(self.engine)
File "/usr/local/lib/python3.7/site-packages/pandas/io/parsers.py", line 1114, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "/usr/local/lib/python3.7/site-packages/pandas/io/parsers.py", line 1891, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas/_libs/parsers.pyx", line 374, in pandas._libs.parsers.TextReader.__cinit__
File "pandas/_libs/parsers.pyx", line 694, in pandas._libs.parsers.TextReader._setup_parser_source
OSError: Expected file path name or file-like object, got <class 'bytes'> type
myLast
list 以这种格式存储一个 url:
'https://test.com/something/example_2020-09-27-10.51PST_ALL.csv'
解决方案
下面应该为你工作
s = requests.get(x, verify=False).content
df = pd.read_csv(io.StringIO(s.decode('utf-8')))