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

如何用Python生成带空格填充固定宽度的逗号分隔CSV文件?

将CSV格式化为列对齐固定宽度的Python实现方法

下面提供两种简便的实现方式,分别基于Python标准库csv和数据分析库pandas:

方法一:使用标准库csv(无需额外安装)

适合轻量场景,完全依赖Python内置模块,无需额外安装依赖:

import csv

# 读取原始CSV数据
with open('original.csv', 'r', newline='', encoding='utf-8') as infile:
    reader = csv.reader(infile)
    rows = list(reader)

if not rows:
    exit()

# 计算每列的最大宽度(以字符串长度为准)
col_widths = [max(len(str(row[col_idx])) for row in rows) for col_idx in range(len(rows[0]))]

# 格式化每行数据:数字右对齐,文本左对齐
formatted_rows = []
for row in rows:
    formatted_cells = []
    for idx, cell in enumerate(row):
        cell_str = str(cell)
        if cell_str.replace('.', '', 1).isdigit():
            formatted_cell = cell_str.rjust(col_widths[idx])
        else:
            formatted_cell = cell_str.ljust(col_widths[idx])
        formatted_cells.append(formatted_cell)
    formatted_rows.append(", ".join(formatted_cells))

# 写入目标文件
with open('tmpfw.csv', 'w', newline='', encoding='utf-8') as outfile:
    outfile.write('\n'.join(formatted_rows))

说明:

  1. 一次性读取所有行数据,避免重复IO操作;
  2. 遍历列计算每列的最大宽度,确保所有单元格内容都能完整显示;
  3. 根据内容类型自动选择对齐方式(数字右对齐、文本左对齐),也可根据需求统一改为左/右对齐;
  4. 最终用, 连接单元格,保证逗号后有空格。

方法二:使用pandas(简洁高效)

适合处理较大的CSV文件,利用pandas的向量化操作提升效率,代码更简洁:

import pandas as pd

# 读取CSV文件(如果有表头,无需设置header=None)
df = pd.read_csv('original.csv', header=None)

# 为每列定义格式化规则:数字右对齐,文本左对齐
formatters = {}
for col in df.columns:
    max_len = df[col].astype(str).apply(len).max()
    if df[col].dtype in ['int64', 'float64']:
        formatters[col] = lambda x, w=max_len: f"{x:>{w}}"
    else:
        formatters[col] = lambda x, w=max_len: f"{x:<{w}}"

# 将DataFrame格式化为指定样式的字符串
formatted_content = df.to_string(formatters=formatters, index=False, col_space=0).replace('  ', ', ')

# 写入目标文件
with open('tmpfw.csv', 'w', encoding='utf-8') as outfile:
    outfile.write(formatted_content)

说明:

  1. 用pandas快速读取CSV并转为DataFrame结构;
  2. 针对每列的数据类型设置对齐和宽度规则;
  3. 利用to_string生成对齐后的文本,再将默认的空格分隔替换为, ;
  4. 如果原始CSV包含表头,去掉header=None参数即可保留表头的格式化效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:02:52