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

使用Pandas read_html导出多表至CSV遇AttributeError问题求助

Fixing AttributeError When Exporting Multiple Tables from HTML to Single CSV

Hey there! Let's break down why you're hitting that AttributeError: 'list' object has no attribute 'to_csv' error and how to fix it.

Why the Error Happens

The pandas.read_html() function doesn't return a single DataFrame—it returns a list of DataFrames, one for each table found in your example.html file. When you try calling .to_csv() directly on that list, Python throws an error because lists don't have that method.

Two Common Solutions for Exporting Multiple Tables to One CSV

Depending on how you want your final CSV structured, use one of these approaches:

1. Combine Tables with the Same Structure (Vertical Stack)

If all your HTML tables have identical columns and you want to stack them into one big table:

import pandas as pd

# Read all tables from the HTML file
table_list = pd.read_html('example.html')

# Combine all DataFrames into one (ignore_index resets row numbers)
combined_table = pd.concat(table_list, ignore_index=True)

# Export to CSV
combined_table.to_csv('combined_output.csv', index=False)
  • ignore_index=True ensures your final table has continuous row numbers instead of keeping the original indices from each individual table.
  • index=False prevents pandas from adding an extra index column to your CSV.

2. Write Tables Separately (With Headers/Blank Lines)

If your tables have different structures and you want to keep them distinct in the CSV (e.g., each table with its own header, separated by blank lines):

import pandas as pd

# Read all tables
table_list = pd.read_html('example.html')

# Open the CSV file in write mode
with open('separate_tables_output.csv', 'w', newline='', encoding='utf-8') as csv_file:
    for idx, table in enumerate(table_list):
        # Only write the header for the first table (adjust if you want headers for all)
        table.to_csv(csv_file, index=False, header=idx == 0)
        # Add a blank line between tables for readability
        csv_file.write('\n')
  • header=idx == 0 tells pandas to write the column headers only once (for the first table). Change this to header=True if you want each table to show its own headers.
  • newline='' avoids extra blank lines in the CSV on Windows systems.

Quick Debug Tip

Before exporting, you can check how many tables were read and inspect their structure:

print(f"Number of tables found: {len(table_list)}")
# Inspect the first table's columns
print(table_list[0].columns)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:13:20