pandas.DataFrame.to_csv
pandas.DataFrame.to_csv
to_csv
DataFrame.to_csv(path_or_buf=None, *, sep=',', na_rep='', float_format=None,
columns=None, header=True, index=True, index_label=None, mode='w', encoding=None,
compression='infer', quoting=None, quotechar='"', lineterminator=None,
chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal='.',
errors='strict', storage_options=None)[source]
Write object to a comma-separated values (csv) file.
Parameters:
path_or_bufstr, path object, file-like object, or None, default None
String, path object (implementing os.PathLike[str]), or file-like object
implementing a write() function. If None, the result is returned as a string. If a
non-binary file object is passed, it should be opened with newline=’’, disabling
universal newlines. If a binary file object is passed, mode might need to contain a
‘b’.
na_repstr, default ‘’
Missing data representation.
columnssequence, optional
Columns to write.
encodingstr, optional
A string representing the encoding to use in the output file, defaults to ‘utf-8’.
encoding is not supported if path_or_buf is a non-binary file object.
May be a dict with key ‘method’ as compression mode and other entries as additional
compression options if compression mode is ‘zip’.
lineterminatorstr, optional
The newline character or character sequence to use in the output file. Defaults to
os.linesep, which depends on the OS in which this method is called (’\n’ for linux,
‘\r\n’ for Windows, i.e.).
chunksizeint or None
Rows to write at a time.
storage_optionsdict, optional
Extra options that make sense for a particular storage connection, e.g. host, port,
username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to
urllib.request.Request as header options. For other URLs (e.g. starting with
“s3://”, and “gcs://”) the key-value pairs are forwarded to fsspec.open. Please see
fsspec and urllib for more details, and for more examples on storage options refer
here.
Returns:
None or str
If path_or_buf is None, returns the resulting csv format as a string. Otherwise
returns None.
See also
read_csv
Load a CSV file into a DataFrame.
to_excel
Write DataFrame to an Excel file.
Examples
df.to_csv(index=False)
'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
compression_opts = dict(method='zip',
archive_name='out.csv')
df.to_csv('out.zip', index=False,
compression=compression_opts)
To write a csv file to a new folder or nested folder you will first need to create
it using either Pathlib or os: