csv --- CSV file reading and writing — Dokumentasi Python 3.15.2
Navigasi index modul | berikut | sebelum | Python » 3.15.2 documentation » The Python standard library » File Formats » csv --- CSV file reading and writing | Tema | csv --- CSV file reading and writing ¶ Kode sumber: Lib/csv.py Format CSV (Comma Separated Values) adalah format impor dan ekspor data yang paling umum digunakan untuk data spreadsheet dan database. Format CSV telah digunakan selama bertahun-tahun sebelum adanya upaya untuk mendeskripsikan format yang distandardisasi pada RFC 4180 .
Kurangnya standar yang terdefinisi dengan baik berarti banyak perbedaan tipis pada data yang dihasilkan dan digunakan dengan penggunaan yang berbeda. Perbedaan tersebut membuat tidak mudah untuk memproses file CSV dari beberapa sumber. Namun, meskipun karakter pembatas dan kutipan berbeda-beda, keseluruhan formatnya cukup mirip sehingga memungkinkan untuk menulis sebuah modul yang secara efisien dapat memanipulasi data tersebut.
The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, "write this data in the format preferred by Excel," or "read data from this file which was generated by Excel," without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats. The csv module's reader and writer objects read and write sequences.
Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes. Lihat juga PEP 305 - API File CSV Python Enhancement Proposal yang mengusulkan penambahan ini ke Python. Module contents ¶ The csv module defines the following functions: csv. reader ( csvfile , / , dialect = 'excel' , ** fmtparams ) ¶ Return a reader object that will process lines from the given csvfile . A csvfile must be an iterable of strings, each in the reader's defined csv format.
A csvfile is most commonly a file-like object or list. If csvfile is a file object, it should be opened with newline='' . [ 1 ] An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.
For full details about the dialect and formatting parameters, see section Dialects and formatting parameters . Each row read from the csv file is returned as a list of strings. No automatic data type conversion is performed unless the QUOTE_NONNUMERIC format option is specified (in which case unquoted fields are transformed into floats). Contoh penggunaan singkat: >>> import csv >>> with open ( 'eggs.csv' , newline = '' ) as csvfile : ... spamreader = csv . reader ( csvfile , delimiter = ' ' , quotechar = '|' ) ... for row in spamreader : ... print ( ', ' . join ( row )) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam where eggs.csv contains: Spam Spam Spam Spam Spam |Baked Beans| Spam |Lovely Spam| |Wonderful Spam| csv. writer ( csvfile , / , dialect = 'excel' , ** fmtparams ) ¶ Return a writer object responsible for converting the user's data into delimited strings on the given file-like object. csvfile can be any object with a write() method.
If csvfile is a file object, it should be opened with newline='' [ 1 ] . An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.
For full details about dialects and formatting parameters, see the Dialects and formatting parameters section. To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string. While this isn't a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written.
Contoh penggunaan singkat: import csv with open ( 'eggs.csv' , 'w' , newline = '' ) as csvfile : spamwriter = csv . writer ( csvfile , delimiter = ' ' , quotechar = '|' , quoting = csv . QUOTE_MINIMAL ) spamwriter . writerow ([ 'Spam' ] * 5 + [ 'Baked Beans' ]) spamwriter . writerow ([ 'Spam' , 'Lovely Spam' , 'Wonderful Spam' ]) which writes eggs.csv containing: Spam Spam Spam Spam Spam |Baked Beans| Spam |Lovely Spam| |Wonderful Spam| csv. register_dialect ( name , / , dialect = 'excel' , ** fmtparams ) ¶ Associate dialect with name . name must be a string.
The dialect can be specified either by passing a sub-class of Dialect , or by fmtparams keyword arguments, or both, with keyword arguments overriding parameters of the dialect. For full details about dialects and formatting parameters, see section Dialects and formatting parameters . csv. unregister_dialect ( name ) ¶ Delete the dialect associated with name from the dialect registry. An Error is raised if name is not a registered dialect name. csv. get_dialect ( name ) ¶ Return the dialect associated with name .
An Error is raised if name is not a registered dialect name. This function returns an immutable Dialect . csv. list_dialects ( ) ¶ Mengembalikan nama dari semua dialek yang terdaftar. csv. field_size_limit ( ) ¶ csv. field_size_limit ( new_limit ) Mengembalikan nilai maksimum ukuran field yang diperbolekan saat ini oleh parser. Jika new_limit diberikan, hal tersebut menjadi limit baru. The csv module defines the following classes: class csv.
DictReader ( f , fieldnames = None , restkey = None , restval = None , dialect = 'excel' , * args , ** kwds ) ¶ Create an object that operates like a regular reader but maps the information in each row to a dict whose keys are given by the optional fieldnames parameter. The fieldnames parameter is a sequence . If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames and will be omitted from the results.
If fieldnames is provided, they will be used and the first row will be included in the results. Regardless of how the fieldnames are determined, the dictionary preserves their original ordering. If a row has more fields than fieldnames, the remaining data is put in a list and stored with the fieldname specified by restkey (which defaults to None ). If a non-blank row has fewer fields than fieldnames, the missing values are filled-in with the value of restval (which defaults to None ).
All other optional or keyword arguments are passed to the underlying reader instance. If the argument passed to fieldnames is an iterator, it will be coerced to a list . Berubah pada versi 3.6: Baris-baris yang dikembalikan sekarang memiliki tipe OrderedDict . Berubah pada versi 3.8: Baris-baris yang dikembalikan sekarang memiliki tipe dict . Contoh penggunaan singkat: >>> import csv >>> with open ( 'names.csv' , newline = '' ) as csvfile : ... reader = csv .
DictReader ( csvfile ) ... for row in reader : ... print ( row [ 'first_name' ], row [ 'last_name' ]) ... Eric Idle John Cleese >>> print ( row ) {'first_name': 'John', 'last_name': 'Cleese'} where names.csv contains: first_name,last_name Eric,Idle John,Cleese class csv. DictWriter ( f , fieldnames , restval = '' , extrasaction = 'raise' , dialect = 'excel' , * args , ** kwds ) ¶ Create an object which operates like a regular writer but maps dictionaries onto output rows.
The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file f . The optional restval parameter specifies the value to be written if t
The rest of this page is on the live site.