如何在Pandas的DataFrame.to_csv()中设置3字符分隔符?
Pandas to_csv 多字符分隔符实现方案
问题背景
尝试在Pandas的DataFrame.to_csv()方法中使用3字符分隔符'&|$',代码如下:
df.to_csv(path_or_buf='Desktop/hello.csv', sep='&|$', lineterminator='&|$')
执行后触发报错:
TypeError: "delimiter" must be a 1-character string
核心原因
Pandas的to_csv()底层依赖Python标准库的csv模块,而该模块仅支持单字符分隔符,无法直接设置多字符分隔符。
可行解决方案
方法1:手动拼接字符串写入
直接将DataFrame的表头和每行数据用目标分隔符拼接成字符串,再写入文件:
# 生成表头行 header = '&|$'.join(df.columns) # 生成数据行 data_rows = ['&|$'.join(map(str, row)) for row in df.values] # 合并所有行 all_lines = [header] + data_rows # 写入文件,默认用换行符分隔行 with open('Desktop/hello.csv', 'w', encoding='utf-8') as f: f.write('\n'.join(all_lines)) # 如果需要用'&|$'作为行终止符,替换为: # f.write('&|$'.join(all_lines) + '&|$')
方法2:借助to_string()生成格式文本
利用to_string()指定分隔符生成字符串,再写入文件:
# 生成带指定分隔符的文本,关闭索引、消除列间距 csv_content = df.to_string(index=False, col_space=0, sep='&|$', justify='left') # 写入文件 with open('Desktop/hello.csv', 'w', encoding='utf-8') as f: f.write(csv_content)
读取注意事项
用上述方法生成的文件不属于标准CSV格式,读取时不能直接用pd.read_csv()的sep参数,需手动处理:
with open('Desktop/hello.csv', 'r', encoding='utf-8') as f: content = f.read().splitlines() # 解析表头和数据 columns = content[0].split('&|$') data = [line.split('&|$') for line in content[1:]] # 重建DataFrame df = pd.DataFrame(data, columns=columns)
内容的提问来源于stack exchange,提问作者Mohammad Miri
相关产品推荐
相关产品推荐

