ZhuLinsen/daily_stock_analysis · error · ValueError
CSV 解析失败:请检查分隔符是否一致、列数是否匹配。常见原因:引号未闭合、某行列数与其他行不一致。原始错误: {e}
Error message
CSV 解析失败:请检查分隔符是否一致、列数是否匹配。常见原因:引号未闭合、某行列数与其他行不一致。原始错误: {e} What it means
Raised when pandas.read_csv (sep=None, python engine, header=None, dtype=str) throws pd.errors.ParserError on the pasted/parsed text. This is a strict-failure branch: structurally malformed delimiter-separated data (ragged rows, unclosed quotes) rather than merely unusual delimiters, since sep=None auto-detects those.
Source
Thrown at src/services/import_parser.py:214
df = pd.DataFrame(rows)
first_row = [str(x).strip().lower() for x in df.iloc[0].tolist()]
if any(c in _CODE_ALIASES or c in _NAME_ALIASES for c in first_row):
df.columns = df.iloc[0]
df = df.iloc[1:].reset_index(drop=True)
return _parse_dataframe(df)
# Try pandas for CSV-like; use dtype=str to preserve leading zeros (e.g. 00700)
try:
df = pd.read_csv(io.StringIO(text), sep=None, engine="python", header=None, dtype=str)
if df is not None and not df.empty:
df = df.fillna("")
first_row = [str(x).strip().lower() for x in df.iloc[0].tolist()]
if any(c in _CODE_ALIASES or c in _NAME_ALIASES for c in first_row):
df.columns = df.iloc[0]
df = df.iloc[1:].reset_index(drop=True)
return _parse_dataframe(df)
except pd.errors.ParserError as e:
raise ValueError(
f"CSV 解析失败:请检查分隔符是否一致、列数是否匹配。"
f"常见原因:引号未闭合、某行列数与其他行不一致。原始错误: {e}"
) from e
except Exception:
pass
# Fallback: plain text, split by comma/tab/space
lines = text.strip().splitlines()
rows = []
for line in lines:
line = line.strip()
if not line:
continue
parts = re.split(r"[\t,;\s]+", line)
if parts:
rows.append(parts)
if not rows:
return []View on GitHub (pinned to 5159bd72e8)
Solutions
- Open the file and fix the malformed line quoted in the original error (row number is in the message)
- Normalize delimiters: re-export from the source (Excel/Sheets) as clean CSV
- If data is loose plain text (codes separated by spaces/tabs per line), simplify to one code per line — the single-column fast path handles it without pandas
Example fix
# before: 600519,'贵州"茅台 <- unclosed quote # after: 600519,贵州茅台 # 00700,腾讯
Defensive patterns
Strategy: fallback
Validate before calling
def is_wellformed_csv(text: str) -> bool:
import pandas as pd, io
try:
pd.read_csv(io.StringIO(text), sep=None, engine='python', header=None, dtype=str)
return True
except pd.errors.ParserError:
return False Try / catch
try:
items = parse_import_from_bytes(data, fn)
except ValueError as e:
if 'CSV 解析失败' in str(e):
# fall back to the per-line loose split the parser itself uses downstream
lines = [l.strip() for l in data.decode('utf-8', 'ignore').splitlines() if l.strip()]
items = parse_import_from_text('\n'.join(l.split(',')[0] for l in lines))
else:
raise Prevention
- Re-export from Excel/Sheets instead of hand-editing CSV
- Prefer one code per line — the single-column fast path avoids pandas entirely
- Check quotes balance when editing quoted fields manually
When it happens
Trigger: A quoted field with an unclosed quote spanning lines; rows with different column counts mid-file; embedded newlines inside quotes combined with mismatched delimiters.
Common situations: Hand-edited CSV where a quote was dropped; mixed delimiter files (some comma, some tab); copy-paste from Excel引入 stray quotes.
Related errors
- 无法识别文件编码,请使用 UTF-8 或 GBK
- invalid_import_file
- efinance 获取数据失败: {failure_message}
- efinance 获取 ETF 数据失败: {failure_message}
- 未安装 Futu OpenAPI SDK;请先执行 `pip install "futu-api==10.8.6808"
AI-assisted analysis of ZhuLinsen/daily_stock_analysis@5159bd72e8 (2026-08-15).
Data as JSON: /api/errors/3237ba6668f36d66.
Report an issue: GitHub.