Hướng dẫn python csv reader seek - trình đọc python csv tìm kiếm

Tôi có một tệp CSV kiểm tra đơn giản:

1,2,3
4,5,6
7,8,9
10,11,12

Tôi đang cố đọc hai dòng đầu tiên, tìm lại một dòng và đọc lại dòng tiếp theo:

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)

Tuy nhiên, tệp đang được đọc hoàn toàn trong cuộc gọi đầu tiên đến

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
6:

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration

Tôi đã thử cài đặt

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
7, nhưng vấn đề tương tự phát sinh. Nếu tôi sử dụng đối tượng tệp một cách rõ ràng để làm
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
8, mọi thứ đều hoạt động tốt. Có một số cách nào để ngăn người đọc CSV đọc theo nhiều dòng tại cuộc gọi
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
6 đầu tiên?

Mã nguồn: lib/csv.py Lib/csv.py


Cái gọi là định dạng CSV (giá trị phân tách bằng dấu phẩy) là định dạng nhập và xuất phổ biến nhất cho bảng tính và cơ sở dữ liệu. Định dạng CSV đã được sử dụng trong nhiều năm trước khi cố gắng mô tả định dạng theo cách được tiêu chuẩn hóa trong RFC 4180. Việc thiếu một tiêu chuẩn được xác định rõ có nghĩa là sự khác biệt tinh tế thường tồn tại trong dữ liệu được tạo ra và tiêu thụ bởi các ứng dụng khác nhau. Những khác biệt này có thể khiến việc xử lý các tệp CSV từ nhiều nguồn. Tuy nhiên, trong khi các trình phân cách và trích dẫn các ký tự khác nhau, định dạng tổng thể tương tự đến mức có thể viết một mô -đun duy nhất có thể thao tác hiệu quả dữ liệu đó, che giấu các chi tiết đọc và viết dữ liệu từ lập trình viên.RFC 4180. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.

Mô -đun

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
0 thực hiện các lớp để đọc và ghi dữ liệu bảng theo định dạng CSV. Nó cho phép các lập trình viên nói, Viết dữ liệu này theo định dạng được ưu tiên bởi excel, dữ liệu hoặc đọc dữ liệu từ tệp này được tạo bởi excel, mà không biết các chi tiết chính xác của định dạng CSV được sử dụng bởi Excel. Các lập trình viên cũng có thể mô tả các định dạng CSV được hiểu bởi các ứng dụng khác hoặc xác định các định dạng CSV có mục đích đặc biệt của riêng họ.

Mô -đun

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
0 Các đối tượng
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
2 và
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 Các chuỗi đọc và ghi. Các lập trình viên cũng có thể đọc và ghi dữ liệu ở dạng từ điển bằng các lớp
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
4 và
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
5.

Xem thêm

PEP 305 - API tệp CSV - CSV File API

Đề xuất tăng cường Python đã đề xuất bổ sung này vào Python.

Nội dung mô -đun

Mô -đun

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
0 xác định các chức năng sau:

csv.Reader (csvfile, dialect = 'excel', ** fmtparams) ¶reader(csvfile, dialect='excel', **fmtparams)

Trả về một đối tượng đầu đọc sẽ lặp lại trên các dòng trong csvfile đã cho. CSVFile có thể là bất kỳ đối tượng nào hỗ trợ giao thức iterator và trả về một chuỗi mỗi lần phương thức

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
7 của nó được gọi - đối tượng tệp và đối tượng danh sách đều phù hợp. Nếu CSVFile là một đối tượng tệp, nó sẽ được mở bằng
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
8. 1 Một tham số phương ngữ tùy chọn có thể được đưa ra được sử dụng để xác định một tập hợp các tham số cụ thể cho một phương ngữ CSV cụ thể. Nó có thể là một ví dụ của một lớp con của lớp
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 hoặc một trong các chuỗi được trả về bởi hàm
>>> 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
0. Các đối số từ khóa FMTPARAM tùy chọn khác có thể được đưa ra để ghi đè các tham số định dạng riêng lẻ trong phương ngữ hiện tại. Để biết chi tiết đầy đủ về các tham số phương ngữ và định dạng, hãy xem Phương ngữ phần và các tham số định dạng.iterator protocol and returns a string each time its
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
7 method is called — file objects and list objects are both suitable. If csvfile is a file object, it should be opened with
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
8. 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
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 class or one of the strings returned by the
>>> 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
0 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.

Mỗi hàng đọc từ tệp CSV được trả về dưới dạng danh sách các chuỗi. Không thực hiện chuyển đổi kiểu dữ liệu tự động nào được thực hiện trừ khi tùy chọn định dạng

>>> 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
1 được chỉ định (trong trường hợp đó các trường chưa được trích xuất được chuyển thành phao).

Một ví dụ sử dụng ngắn:

>>> 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

csv.Writer (csvfile, dialect = 'excel', ** fmtparams) ¶writer(csvfile, dialect='excel', **fmtparams)

Trả về một đối tượng nhà văn chịu trách nhiệm chuyển đổi dữ liệu của người dùng thành các chuỗi được phân định trên đối tượng giống như tệp đã cho. CSVFile có thể là bất kỳ đối tượng nào với phương thức

>>> 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
2. Nếu CSVFILE là đối tượng tệp, nó sẽ được mở bằng
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
8 1. Một tham số phương ngữ tùy chọn có thể được cung cấp được sử dụng để xác định một tập hợp các tham số cụ thể cho một phương ngữ CSV cụ thể. Nó có thể là một ví dụ của một lớp con của lớp
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 hoặc một trong các chuỗi được trả về bởi hàm
>>> 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
0. Các đối số từ khóa FMTPARAM tùy chọn khác có thể được đưa ra để ghi đè các tham số định dạng riêng lẻ trong phương ngữ hiện tại. Để biết chi tiết đầy đủ về phương ngữ và tham số định dạng, hãy xem phần Phương ngữ và định dạng. Để làm cho nó dễ dàng nhất có thể để giao tiếp với các mô -đun triển khai API DB, giá trị
>>> 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
6 được viết dưới dạng chuỗi trống. Mặc dù đây không phải là một phép biến đổi có thể đảo ngược, nhưng nó giúp việc gửi các giá trị dữ liệu SQL NULL dễ dàng hơn vào các tệp CSV mà không xử lý dữ liệu được trả về từ cuộc gọi
>>> 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
7. Tất cả các dữ liệu không chuỗi khác được xâu chuỗi với
>>> 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
8 trước khi được viết.Dialects and Formatting Parameters section. To make it as easy as possible to interface with modules which implement the DB API, the value
>>> 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
6 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
>>> 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
7 call. All other non-string data are stringified with
>>> 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
8 before being written.

Một ví dụ sử dụng ngắn:

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'])

csv.register_dialect (tên [, phương ngữ [, ** fmtparams]]) ¶register_dialect(name[, dialect[, **fmtparams]])

Liên kết phương ngữ với tên. Tên phải là một chuỗi. Phương ngữ có thể được chỉ định bằng cách truyền một lớp phụ là

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 hoặc bằng các đối số từ khóa của fmtparams hoặc cả hai, với các đối số từ khóa ghi đè các tham số của phương ngữ. Để biết chi tiết đầy đủ về phương ngữ và tham số định dạng, hãy xem Phương ngữ và các tham số định dạng.Dialects and Formatting Parameters.

csv.unregister_dialect (tên) ¶unregister_dialect(name)

Xóa phương ngữ được liên kết với tên từ sổ đăng ký phương ngữ. Một

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'])
0 được nêu ra nếu tên không phải là tên phương ngữ đã đăng ký.

csv.get_dialect (tên) ¶get_dialect(name)

Trả về phương ngữ liên quan đến tên. Một

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'])
0 được nêu ra nếu tên không phải là tên phương ngữ đã đăng ký. Hàm này trả về một
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 bất biến.

csv.list_dialects () ¶list_dialects()

Trả về tên của tất cả các phương ngữ đã đăng ký.

csv.field_size_limit ([new_limit]) ¶field_size_limit([new_limit])

Trả về kích thước trường tối đa hiện tại cho phép bởi trình phân tích cú pháp. Nếu new_limit được đưa ra, điều này sẽ trở thành giới hạn mới.

Mô -đun

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
0 xác định các lớp sau:

classcsv.dictreader (f, fieldNames = none, restKey = none, restVal = none, dialect = 'excel', *args, ** kwds) ¶csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

Tạo một đối tượng hoạt động giống như một trình đọc thông thường nhưng ánh xạ thông tin theo mỗi hàng thành một

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'])
4 có các khóa được cung cấp bởi tham số tên trường tùy chọn.

Tham số FieldName là một chuỗi. Nếu các tên trường bị bỏ qua, các giá trị trong hàng đầu tiên của tệp F sẽ được sử dụng làm tên trường. Bất kể các tên trường được xác định như thế nào, từ điển bảo tồn thứ tự ban đầu của chúng.sequence. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames. Regardless of how the fieldnames are determined, the dictionary preserves their original ordering.

Nếu một hàng có nhiều trường hơn các tên trường, dữ liệu còn lại được đặt trong danh sách và được lưu trữ với tên trường được chỉ định bởi RestKey (mặc định là

>>> 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
6). Nếu một hàng không trống có ít trường hơn các tên trường, các giá trị bị thiếu được điền vào với giá trị của restVal (mặc định là
>>> 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
6).

Tất cả các đối số từ khóa hoặc tùy chọn khác được chuyển đến thể hiện cơ bản

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
2.

Đã thay đổi trong phiên bản 3.6: Các hàng được trả về hiện thuộc loại

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'])
8.Returned rows are now of type
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'])
8.

Đã thay đổi trong phiên bản 3.8: Các hàng được trả về hiện thuộc loại

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'])
4.Returned rows are now of type
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'])
4.

Một ví dụ sử dụng ngắn:

>>> 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'}

classcsv.dictwriter (f, fieldNames, restVal = '', extrasaction = 'rise', dialect = 'excel', *args, ** kwds) ¶csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

Tạo một đối tượng hoạt động giống như một nhà văn thông thường nhưng ánh xạ từ điển lên các hàng đầu ra. Tham số FieldNaming là

>>> 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'}
0 của các khóa xác định thứ tự trong đó các giá trị trong từ điển được truyền đến phương thức
>>> 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'}
1 được ghi vào tệp f. Tham số restVal tùy chọn chỉ định giá trị sẽ được viết nếu từ điển bị thiếu một khóa trong các tên trường. Nếu từ điển được chuyển đến phương thức
>>> 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'}
1 chứa một khóa không tìm thấy trong các tên trường, tham số ngoại lệ tùy chọn cho biết hành động nào sẽ thực hiện. Nếu nó được đặt thành
>>> 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'}
3, giá trị mặc định,
>>> 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'}
4 được nâng lên. Nếu nó được đặt thành
>>> 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'}
5, các giá trị bổ sung trong từ điển sẽ bị bỏ qua. Bất kỳ đối số từ khóa hoặc tùy chọn nào khác được chuyển đến thể hiện cơ bản
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3.

Lưu ý rằng không giống như lớp

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
4, tham số tên trường của lớp
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
5 không phải là tùy chọn.

Một ví dụ sử dụng ngắn:

import csv

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

classcsv.dialect¶csv.Dialect

Lớp

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 là một lớp container có các thuộc tính chứa thông tin về cách xử lý DoubleQuote, Whitespace, Delimiter, v.v. Do thiếu thông số kỹ thuật CSV nghiêm ngặt, các ứng dụng khác nhau tạo ra dữ liệu CSV khác nhau.
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 Các trường hợp xác định cách thức hoạt động của
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
2 và ____23.

Tất cả các tên

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 có sẵn được trả về bởi
>>> 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
0 và chúng có thể được đăng ký với các lớp
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
2 và
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 cụ thể thông qua các hàm khởi đầu (
import csv

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
7) như thế này:

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^

classcsv.excel¶csv.excel

Lớp

import csv

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
8 xác định các thuộc tính thông thường của tệp CSV do Excel tạo. Nó được đăng ký với tên phương ngữ
import csv

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
9.

classcsv.excel_tab¶csv.excel_tab

Lớp

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
0 xác định các thuộc tính thông thường của tệp được phân phối theo tab do Excel tạo. Nó được đăng ký với tên phương ngữ
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
1.

classcsv.unix_dialect¶ csv.unix_dialect

Lớp

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
2 xác định các thuộc tính thông thường của tệp CSV được tạo trên các hệ thống UNIX, tức là sử dụng
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
3 làm đầu hủy dòng và trích dẫn tất cả các trường. Nó được đăng ký với tên phương ngữ
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
4.

Mới trong phiên bản 3.2.

classcsv.sniffer¶csv.Sniffer

Lớp

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
5 được sử dụng để suy ra định dạng của tệp CSV.

Lớp

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
5 cung cấp hai phương pháp:

Sniff (Mẫu, Delimiter = none) ¶(sample, delimiters=None)

Phân tích mẫu đã cho và trả về lớp con

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 phản ánh các tham số được tìm thấy. Nếu tham số DELIMITER tùy chọn được đưa ra, nó được hiểu là một chuỗi chứa các ký tự phân cách hợp lệ có thể có.

Phân tích văn bản mẫu (được cho là ở định dạng CSV) và trả về

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
8 nếu hàng đầu tiên dường như là một loạt các tiêu đề cột. Kiểm tra từng cột, một trong hai tiêu chí chính sẽ được xem xét để ước tính nếu mẫu có chứa tiêu đề:

  • Các hàng thứ hai đến n có chứa các giá trị số

  • Các hàng thứ hai đến n có chứa các chuỗi trong đó ít nhất một giá trị chiều dài khác nhau so với tiêu đề giả định của cột đó.

Hai mươi hàng sau hàng đầu tiên được lấy mẫu; Nếu hơn một nửa cột + hàng đáp ứng các tiêu chí,

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
8 sẽ được trả về.

Ghi chú

Phương pháp này là một heuristic thô và có thể tạo ra cả tích cực và tiêu cực giả.

Một ví dụ cho

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
5 Sử dụng:

with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...

Mô -đun

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
0 xác định các hằng số sau:

csv.quote_all¶QUOTE_ALL

Hướng dẫn các đối tượng

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 để trích dẫn tất cả các trường.

csv.quote_minimal¶QUOTE_MINIMAL

Hướng dẫn các đối tượng

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 chỉ trích dẫn các trường có chứa các ký tự đặc biệt như Delimiter, Quotechar hoặc bất kỳ ký tự nào trong lineterminator.

csv.quote_nonnumeric¶QUOTE_NONNUMERIC

Hướng dẫn các đối tượng

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 để trích dẫn tất cả các trường không phải là số.

Hướng dẫn người đọc chuyển đổi tất cả các trường không được trích xuất để gõ float.

csv.quote_none¶QUOTE_NONE

Hướng dẫn các đối tượng

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 không bao giờ trích dẫn các trường. Khi dấu phân cách hiện tại xảy ra trong dữ liệu đầu ra, nó được đi trước bởi ký tự Escapechar hiện tại. Nếu Escapechar không được thiết lập, người viết sẽ tăng
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'])
0 nếu có bất kỳ nhân vật nào yêu cầu trốn thoát đều gặp phải.

Hướng dẫn

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
2 không thực hiện xử lý đặc biệt các ký tự trích dẫn.

Mô -đun

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
0 xác định ngoại lệ sau:

Exceptioncsv.error¶csv.Error

Được nâng lên bởi bất kỳ chức năng nào khi phát hiện lỗi.

Phương ngữ và các tham số định dạng

Để dễ dàng hơn để chỉ định định dạng của các bản ghi đầu vào và đầu ra, các tham số định dạng cụ thể được nhóm lại thành các phương ngữ. Một phương ngữ là một lớp con của lớp

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 có một tập hợp các phương thức cụ thể và một phương thức
import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
0 duy nhất. Khi tạo các đối tượng
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
2 hoặc
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3, lập trình viên có thể chỉ định một chuỗi hoặc một lớp con của lớp
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 làm tham số phương ngữ. Ngoài hoặc thay vì tham số phương ngữ, lập trình viên cũng có thể chỉ định các tham số định dạng riêng lẻ, có cùng tên với các thuộc tính được xác định dưới đây cho lớp
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9.

Phương ngữ hỗ trợ các thuộc tính sau:

Phương ngữ.delimiter¶delimiter

Một chuỗi một ký tự được sử dụng để tách các trường. Nó mặc định là

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
5.

Phương ngữ.doublequote¶doublequote

Kiểm soát cách các trường hợp của quotechar xuất hiện bên trong một trường nên được trích dẫn. Khi

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
8, nhân vật được nhân đôi. Khi
import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
7, Escapechar được sử dụng làm tiền tố cho quotechar. Nó mặc định là
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
8.

Trên đầu ra, nếu DoubleQuote là

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
7 và không có Escapechar được đặt,
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'])
0 sẽ được nâng lên nếu tìm thấy một quotechar trong một trường.

Phương ngữ.escapechar¶escapechar

Một chuỗi một vật nhân được người viết sử dụng để thoát khỏi dấu phân cách nếu trích dẫn được đặt thành

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
01 và quotechar nếu doublequote là
import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
7. Khi đọc, Escapechar loại bỏ bất kỳ ý nghĩa đặc biệt nào khỏi nhân vật sau. Nó mặc định là
>>> 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
6, vô hiệu hóa việc thoát ra.

Đã thay đổi trong phiên bản 3.11: Không được phép Escapechar trống.An empty escapechar is not allowed.

Phương ngữ.LineterMinator¶lineterminator

Chuỗi được sử dụng để chấm dứt các dòng được tạo bởi

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3. Nó mặc định là
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
05.

Ghi chú

Phương pháp này là một heuristic thô và có thể tạo ra cả tích cực và tiêu cực giả.

Một ví dụ cho
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
5 Sử dụng:
quotechar

Mô -đun

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
0 xác định các hằng số sau:

csv.quote_all¶An empty quotechar is not allowed.

Hướng dẫn các đối tượng
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 để trích dẫn tất cả các trường.
quoting

csv.quote_minimal¶Module Contents) and defaults to

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
11.

Hướng dẫn các đối tượng
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 chỉ trích dẫn các trường có chứa các ký tự đặc biệt như Delimiter, Quotechar hoặc bất kỳ ký tự nào trong lineterminator.
skipinitialspace

csv.quote_nonnumeric¶

Hướng dẫn các đối tượng
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 để trích dẫn tất cả các trường không phải là số.
strict

Hướng dẫn người đọc chuyển đổi tất cả các trường không được trích xuất để gõ float.

csv.quote_none¶

Hướng dẫn các đối tượng

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
3 không bao giờ trích dẫn các trường. Khi dấu phân cách hiện tại xảy ra trong dữ liệu đầu ra, nó được đi trước bởi ký tự Escapechar hiện tại. Nếu Escapechar không được thiết lập, người viết sẽ tăng
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'])
0 nếu có bất kỳ nhân vật nào yêu cầu trốn thoát đều gặp phải.

Hướng dẫn
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
2 không thực hiện xử lý đặc biệt các ký tự trích dẫn.
__next__()

Mô -đun

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
0 xác định ngoại lệ sau:

Exceptioncsv.error¶

csvreader.dialect¶dialect

Một mô tả chỉ đọc của phương ngữ được sử dụng bởi trình phân tích cú pháp.

csvreader.line_num¶line_num

Số lượng dòng đọc từ trình lặp nguồn. Điều này không giống với số lượng hồ sơ được trả về, vì các bản ghi có thể trải rộng nhiều dòng.

Các đối tượng DicTreader có thuộc tính công khai sau:

csvreader.fieldnames¶fieldnames

Nếu không được truyền dưới dạng tham số khi tạo đối tượng, thuộc tính này sẽ được khởi tạo khi truy cập đầu tiên hoặc khi bản ghi đầu tiên được đọc từ tệp.

Người viết đối tượng

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
23 Đối tượng (
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
5 Các trường hợp và đối tượng được trả về bởi hàm
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
25) có các phương thức công khai sau. Một hàng phải là một chuỗi hoặc số có thể lặp lại cho các đối tượng
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
23 và các tên trường ánh xạ từ điển đến các chuỗi hoặc số (bằng cách truyền chúng qua
>>> 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
8 trước tiên) cho các đối tượng
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
5. Lưu ý rằng các số phức được viết ra được bao quanh bởi parens. Điều này có thể gây ra một số vấn đề cho các chương trình khác đọc các tệp CSV (giả sử chúng hỗ trợ các số phức tạp).

csvwriter.writerow (hàng) ¶writerow(row)

Viết tham số hàng vào đối tượng tệp của người viết, được định dạng theo

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
9 hiện tại. Trả về giá trị trả về của cuộc gọi cho phương thức ghi của đối tượng tệp bên dưới.

Đã thay đổi trong phiên bản 3.5: Đã thêm hỗ trợ của Iterables tùy ý.Added support of arbitrary iterables.

csvwriter.writerows (hàng) ¶writerows(rows)

Viết tất cả các phần tử trong các hàng (có thể lặp lại của các đối tượng hàng như được mô tả ở trên) vào đối tượng tệp của người viết, được định dạng theo phương ngữ hiện tại.

Các đối tượng của người viết có thuộc tính công khai sau:

csvwriter.dialect¶dialect

Một mô tả chỉ đọc của phương ngữ được sử dụng bởi người viết.

Các đối tượng DictWriter có phương thức công khai sau:

Viết một hàng với các tên trường (như được chỉ định trong hàm tạo) vào đối tượng tệp của người viết, được định dạng theo phương ngữ hiện tại. Trả về giá trị trả về của cuộc gọi

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
30 được sử dụng trong nội bộ.

Mới trong phiên bản 3.2.

Ví dụ;

Ví dụ đơn giản nhất về việc đọc tệp CSV:

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Đọc một tệp có định dạng thay thế:

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
0

Ví dụ viết đơn giản nhất có thể tương ứng là:

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
1

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
31 được sử dụng để mở tệp CSV để đọc, nên tệp sẽ được giải mã thành Unicode bằng cách sử dụng mã hóa mặc định hệ thống (xem
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
32). Để giải mã một tệp bằng cách sử dụng mã hóa khác, hãy sử dụng đối số
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
33 của Open:

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
2

Điều tương tự cũng áp dụng cho việc viết trong một cái gì đó không phải là mã hóa mặc định của hệ thống: Chỉ định đối số mã hóa khi mở tệp đầu ra.

Đăng ký một phương ngữ mới:

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
3

Sử dụng tiên tiến hơn một chút của người đọc - lỗi bắt và báo cáo:

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
4

Và trong khi mô -đun không trực tiếp hỗ trợ các chuỗi phân tích cú pháp, nó có thể dễ dàng thực hiện:

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
5

Chú thích

1(1,2)(1,2)

Nếu

pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
8 không được chỉ định, các dòng mới được nhúng bên trong các trường được trích dẫn sẽ không được giải thích chính xác và trên các nền tảng sử dụng các lớp lót
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
35 trên viết thêm một
import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    pos = f.tell()
    print 'pos: {0}'.format(pos)
    print reader.next()

    f.seek(pos)
    pos = f.tell()
    print 'pos: {0}'.format(pos)

    print reader.next()
    pos = f.tell()
    print 'pos: {0}'.format(pos)
36 sẽ được thêm vào. Luôn luôn an toàn khi chỉ định
pos: 0
['1', '2', '3']
pos: 27
['4', '5', '6']
pos: 27
Traceback (most recent call last):
  File "", line 15, in 
StopIteration
8, vì mô -đun CSV thực hiện xử lý dòng mới (phổ quát) của riêng mình.universal) newline handling.