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

使用Pandas的df.to_csv生成无分隔符TXT文件遇错求助

Solution for Creating Delimiter-Free TXT File with Pandas

Hey there! That error makes total sense—under the hood, pandas uses Python's built-in csv module to handle the to_csv() method, and that module strictly requires the delimiter/separator to be a 1-character string. Passing an empty string just violates that rule, hence the TypeError.

Here are two reliable alternatives to get the delimiter-free text file you're aiming for:

1. Concatenate row values directly then write to file

This method ensures every row's column values are joined into a single, continuous string with no separators at all:

# For each row, convert all values to strings and concatenate them
delimiter_free_rows = df1.apply(lambda row: ''.join(map(str, row)), axis=1)

# Write the result to your text file
delimiter_free_rows.to_csv(
    'C:/Users/junxonm/Desktop/Filetest.txt',
    index=False,
    header=False
)

This works because we're first transforming each row into a single string, then using to_csv() just to write those strings (with no extra delimiters needed, since each entry is already a single value).

2. Use to_string() for formatted output (if alignment is okay)

If you're okay with slight spacing between columns (from default alignment) but no explicit delimiter, you can convert the DataFrame to a string first and write it directly:

# Convert DataFrame to a string without index or header
df_text = df1.to_string(index=False, header=False)

# Write the string to file
with open('C:/Users/junxonm/Desktop/Filetest.txt', 'w') as output_file:
    output_file.write(df_text)

Note: This will keep columns aligned with spaces, so it's not completely delimiter-free in terms of spacing, but it avoids using a defined separator like commas or tabs.

Either approach should solve your problem—pick the one that matches exactly what you want for your text file content!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:42:58