How to Write CSV Files with Custom Formatting in Pandas

Pandas makes it easy to write DataFrames to CSV files. You can also customize the output format. This gives you control over how your data is saved.

Specifying the Delimiter

By default, Pandas uses commas (,) as delimiters. You can change this using the sep argument in to_csv.

Example (Using a Tab as a Delimiter)

import pandas as pd

data = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data)
df.to_csv("my_data.txt", sep="\t") # Saves as tab-separated

Controlling Quotes

Pandas uses quotes (“) to enclose fields with special characters. You can control this with the quoting argument. Use csv.QUOTE_NONNUMERIC to quote only non-numeric values.

Example (Quoting Non-Numeric Values)

import pandas as pd
import csv

data = {'col1': [1, 2], 'col2': ['a,b', 'c']}
df = pd.DataFrame(data)
df.to_csv("my_data.csv", quoting=csv.QUOTE_NONNUMERIC)

Other Formatting Options

You can also control the line terminator using lineterminator. The default is \r\n on Windows and \n on other systems. You can also specify the encoding with the encoding parameter.

Example (Using a different line terminator)

import pandas as pd

data = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data)
df.to_csv("my_data.csv", lineterminator='\n')

For more advanced control, consult the to_csv documentation. It has many more options.

Leave a Reply