Write object to a comma-separated values (csv) file.
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â.
String of length 1. Field delimiter for the output file.
Missing data representation.
Format string for floating point numbers. If a Callable is given, it takes precedence over other numeric formatting parameters, like decimal.
Columns to write.
Write out the column names. If a list of strings is given it is assumed to be aliases for the column names.
Write row names (index).
Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used. A sequence should be given if the object uses MultiIndex. If False do not print fields for index names. Use index_label=False for easier importing in R.
Forwarded to either open(mode=) or fsspec.open(mode=) to control the file opening. Typical values include:
âwâ, truncate the file first.
âxâ, exclusive creation, failing if the file already exists.
âaâ, append to the end of file if it exists.
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.
For on-the-fly compression of the output data. If âinferâ and âpath_or_bufâ is path-like, then detect compression from the following extensions: â.gzâ, â.bz2â, â.zipâ, â.xzâ, â.zstâ, â.tarâ, â.tar.gzâ, â.tar.xzâ or â.tar.bz2â (otherwise no compression). Set to None
for no compression. Can also be a dict with key 'method'
set to one of {'zip'
, 'gzip'
, 'bz2'
, 'zstd'
, 'xz'
, 'tar'
} and other key-value pairs are forwarded to zipfile.ZipFile
, gzip.GzipFile
, bz2.BZ2File
, zstandard.ZstdCompressor
, lzma.LZMAFile
or tarfile.TarFile
, respectively. As an example, the following could be passed for faster compression and to create a reproducible gzip archive: compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}
.
Added in version 1.5.0: Added support for .tar files.
May be a dict with key âmethodâ as compression mode and other entries as additional compression options if compression mode is âzipâ.
Passing compression options as keys in dict is supported for compression modes âgzipâ, âbz2â, âzstdâ, and âzipâ.
Defaults to csv.QUOTE_MINIMAL. If you have set a float_format then floats are converted to strings and thus csv.QUOTE_NONNUMERIC will treat them as non-numeric.
String of length 1. Character used to quote fields.
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.).
Changed in version 1.5.0: Previously was line_terminator, changed for consistency with read_csv and the standard library âcsvâ module.
Rows to write at a time.
Format string for datetime objects.
Control quoting of quotechar inside a field.
String of length 1. Character used to escape sep and quotechar when appropriate.
Character recognized as decimal separator. E.g. use â,â for European data.
Specifies how encoding and decoding errors are to be handled. See the errors argument for open()
for a full list of options.
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.
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
Create âout.csvâ containing âdfâ without indices
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'], ... 'mask': ['red', 'purple'], ... 'weapon': ['sai', 'bo staff']}) >>> df.to_csv('out.csv', index=False)
Create âout.zipâ containing âout.csvâ
>>> 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:
>>> from pathlib import Path >>> filepath = Path('folder/subfolder/out.csv') >>> filepath.parent.mkdir(parents=True, exist_ok=True) >>> df.to_csv(filepath)
>>> import os >>> os.makedirs('folder/subfolder', exist_ok=True) >>> df.to_csv('folder/subfolder/out.csv')
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4