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:
- Incorrect Header Writing: The
csv.writerow()method expects a single iterable (like a list) as its argument. You tried passing individual characters plus anend="\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. - Broken Loop Logic: Your nested loops (
jandk) wouldn't generate 10000 rows of data; they'd create a mismatched number of rows and values instead. - 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-Jheader list, then pass it towriterow()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, whichwriterow()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 totable.tsvfor clarity.
内容的提问来源于stack exchange,提问作者R.N
相关产品推荐
相关产品推荐

