Python Glossary Русский

all Python 3Files & I/Oterm

csv

csv

The csv module reads and writes CSV files. reader/writer work with rows, DictReader/DictWriter with dictionaries.

Syntax

import csv
csv.reader(f)
csv.writer(f)

Open the file with newline='' — the module handles line endings itself, and without it Windows gives you a blank line between every record. reader hands back every field as a string: '30' stays text until you convert it yourself. DictReader takes the field names from the first line, so if the file has no header row, pass fieldnames explicitly or your first data record silently becomes the header.

Examples

import csv, io
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(['name', 'age'])
writer.writerow(['Alice', 30])
print(output.getvalue())  # → name,age / Alice,30
output.seek(0)
for row in csv.reader(output):
    print(row)  # → ['name', 'age'] / ['Alice', '30'] — всё читается строками
import csv, io
# Запись в файл
with open('data.csv','w',newline='',encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerows([['a',1],['b',2]])
    # Чтение с другим разделителем
    data = 'a;b;c\n1;2;3'
    for row in csv.reader(io.StringIO(data), delimiter=';'):
        print(row)  # → ['a','b','c'] / ['1','2','3']
        # Настройка quoting
        output3 = io.StringIO()
        w2 = csv.writer(output3, quoting=csv.QUOTE_ALL)
        w2.writerow(['hello world', '42', 'a,b'])
        print(output3.getvalue())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy