csv — CSV file reading and writing — Python 3.15.2 documentation
Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Формати файлів » csv — CSV file reading and writing | Theme | csv — CSV file reading and writing ¶ Вихідний код: Lib/csv.py Так званий формат CSV (значення, розділені комами) є найпоширенішим форматом імпорту та експорту для електронних таблиць і баз даних.
Формат CSV використовувався протягом багатьох років до того, як його спробували описати стандартизованим способом у RFC 4180 . Відсутність чітко визначеного стандарту означає, що часто існують тонкі відмінності в даних, які створюються та споживаються різними програмами.
Ці відмінності можуть дратувати обробку файлів CSV із кількох джерел. Тим не менш, хоча розділювачі та символи лапок відрізняються, загальний формат досить схожий, щоб можна було написати один модуль, який може ефективно маніпулювати такими даними, приховуючи деталі читання та запису даних від програміста.
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. Дивись також PEP 305 - API файлів CSV Пропозиція вдосконалення Python, яка пропонує це доповнення до 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).
Короткий приклад використання: >>> 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.
Короткий приклад використання: 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 ) ¶ Пов’яжіть діалект з ім’ям . ім’я має бути рядком.
Діалект можна вказати або шляхом передачі підкласу Dialect , або за допомогою аргументів ключового слова fmtparams , або обох, причому аргументи ключового слова замінюють параметри діалекту. Щоб отримати повну інформацію про діалекти та параметри форматування, перегляньте розділ Dialects and formatting parameters . csv. unregister_dialect ( name ) ¶ Видаліть діалект, пов’язаний з name , із реєстру діалектів.
Якщо name не є зареєстрованою назвою діалекту, виникає помилка Error . csv. get_dialect ( name ) ¶ Повертає діалект, пов’язаний з ім’ям . Якщо name не є зареєстрованою назвою діалекту, виникає помилка Error . Ця функція повертає незмінний Dialect . csv. list_dialects ( ) ¶ Повернути назви всіх зареєстрованих діалектів. csv. field_size_limit ( ) ¶ csv. field_size_limit ( new_limit ) Повертає поточний максимальний розмір поля, дозволений аналізатором.
Якщо задано new_limit , це стає новим лімітом. The csv module defines the following classes: class csv. DictReader ( f , fieldnames = None , restkey = None , restval = None , dialect = 'excel' , * args , ** kwds ) ¶ Створіть об’єкт, який працює як звичайний читач, але зіставляє інформацію в кожному рядку з dict , ключі якого надаються необов’язковим параметром fieldnames .
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 a
The rest of this page is on the live site.