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

Python写入CSV文件报错:无法生成10列10000行随机数CSV

Fixing Your CSV Generation Code

Hey there! Let's work through the issues in your code so you can successfully generate that 10-column, 10000-row CSV file filled with random numbers.

What Was Going Wrong

Let's break down the key issues in your original snippet:

  1. Incorrect Header Writing: The csv.writerow() method expects a single iterable (like a list) as its argument. You tried passing individual characters plus an end="\t" parameter, which is invalid—this would throw an error and also write each column name to its own line instead of a single header row.
  2. Broken Loop Logic: Your nested loops (j and k) wouldn't generate 10000 rows of data; they'd create a mismatched number of rows and values instead.
  3. Optional: Format Confusion: You set delimiter="\t" (tab-separated) but named the file .csv. This works, but it's technically a TSV file—we'll note how to adjust this if needed.

Corrected Full Code

Here's the fixed version with comments explaining each step:

import random
import csv

# Create the header list (A to J) in one go
column_headers = [chr(i) for i in range(ord('A'), ord('J') + 1)]

# Open the file for writing; add newline='' to avoid extra blank lines on Windows
with open('table.csv', 'w', newline='') as csv_file:
    # Use default comma delimiter for proper CSV; use delimiter="\t" if you want TSV
    writer = csv.writer(csv_file)
    
    # Write the header row first
    writer.writerow(column_headers)
    
    # Generate and write 10000 rows of data
    for _ in range(10000):
        # Create a list of 10 random integers between 1 and 1000
        row_values = [random.randint(1, 1000) for _ in range(10)]
        # Write the row to the file
        writer.writerow(row_values)

Key Fixes Explained

  • Header Handling: We use a list comprehension to build the A-J header list, then pass it to writerow() to write all column names in a single row.
  • Row Generation: A simple loop over range(10000) creates exactly 10000 rows. Each row is a list of 10 random numbers, which writerow() correctly writes as a single line in the file.
  • Windows Compatibility: The newline='' parameter prevents the csv module from adding extra blank lines between rows on Windows systems (this is a recommended best practice from Python's official docs).
  • Format Adjustment: If you actually want tab-separated values instead of comma-separated, change the writer line to writer = csv.writer(csv_file, delimiter="\t") and rename the file to table.tsv for clarity.

内容的提问来源于stack exchange,提问作者R.N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:20:28