Hướng dẫn csv-diff python code - mã python csv-diff

import pandas as pd
import sys
import csv

def dataframe_difference(df1: pd.DataFrame, df2: pd.DataFrame, csvfile, which=None):
    """Find rows which are different between two DataFrames."""
    comparison_df = df1.merge(
        df2,
        indicator=True,
        how='outer'
    )
    if which is None:
        diff_df = comparison_df[comparison_df['_merge'] != 'both']
    else:
        diff_df = comparison_df[comparison_df['_merge'] == which]
    diff_df.to_csv(csvfile)
    return diff_df


if __name__ == '__main__':
    df1 = pd.read_csv(sys.argv[1], sep=',')    
    df2 = pd.read_csv(sys.argv[2], sep=',')

    df1.sort_values(sys.argv[3])
    df2.sort_values(sys.argv[3])
    #df1.drop(df1.columns[list(map(int, sys.argv[4].split()))], axis = 1, inplace = True)
    #df2.drop(df2.columns[list(map(int, sys.argv[4].split()))], axis = 1, inplace = True)

    print(dataframe_difference(df1, df2, sys.argv[5]))

Để sử dụng chạy::

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv

Trong trường hợp bạn muốn bỏ bất kỳ cột nào từ sự so sánh, phần chưa kết hợp

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
6 và chạy

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv

Trong đó

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
7 là số cột để thả, chỉ mục bắt đầu từ 0.

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

Nội phân chính

  • Nội dung mô -đun
  • Phương ngữ và các tham số định dạng
  • Đối tượng đọc
  • Người viết đối tượng
  • python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
    
    84 Đối tượng (
    python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
    
    3 Các trường hợp và đối tượng được trả về bởi hàm
    python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
    
    86) 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
    python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
    
    84 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', '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 trước tiên) cho các đối tượng
    python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
    
    3. 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).
  • ________ 190 ________ 191 (hàng) ¶
  • Viết tham số hàng vào đối tượng tệp của người viết, được định dạng theo
    python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
    
    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 ý.


________ 190 ________ 194 (hàng) ¶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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
8 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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
8 Các đối tượng
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
0 và
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1 đọc và ghi các chuỗi. 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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
2 và
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
3.

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
8 xác định các chức năng sau:

________ 25 ________ 26 (CSVFILE, Phương ngữ = 'Excel', ** fmtparams) ¶(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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
7 method is called — file objects and list objects are both suitable. If csvfile is a file object, it should be opened with
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
________ 25 ________ 33 (csvfile, dialect = 'excel', ** fmtparams) ¶(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
4. Nếu CSVFILE là đối tượng tệp, nó sẽ được mở bằng
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
8 đượ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
9. 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', '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 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
8 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
9 call. All other non-string data are stringified with
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 before being written.

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
________ 25 ________ 33 (csvfile, dialect = 'excel', ** fmtparams) ¶(name[, dialect[, **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
4. Nếu CSVFILE là đối tượng tệp, nó sẽ được mở bằng
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
8 đượ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
9. 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', '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 trước khi được viết.Dialects and Formatting Parameters.

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'])
________ 25 ________ 42 (tên [, phương ngữ [, ** fmtparams]])(name)

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à

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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.

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

________ 25 ________ 48 (Tên) ¶()

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'])
6 đượ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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
9 bất biến.

________ 25 ________ 52 ()([new_limit])

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

________ 25 ________ 54 ([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.(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

Mô -đun

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
8 xác định các lớp sau:

Lớp ________ 25 ________ 57 (f, fieldNames = none, restKey = none, restVal = none, dialect = 'excel', *args, ** kwds) ¶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
8). 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
8).

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
0.

Đã 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('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'})
2.Returned rows are now of type
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'})
2.

Đã 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('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'}
8.Returned rows are now of type
>>> 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'}
8.

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'}
Lớp ________ 25 ________ 65 (f, fieldNames, restVal = '', extrasaction = 'rise', dialect = 'excel', *args, ** kwds) ¶(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ố FieldName là

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'})
6 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', '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 đượ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', '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 chứa một khóa không tìm thấy trong các tên trường, tham số phụ thuộc 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', '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, giá trị mặc định,
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
0 sẽ được nâng lên. Nếu nó được đặt thành
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
1, 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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1.

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
2, tham số tên trường của lớp
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
3 không phải là tùy chọn.

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'}
Lớp ________ 25 ________ 65 (f, fieldNames, restVal = '', extrasaction = 'rise', 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ố FieldName là

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'})
6 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', '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 đượ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', '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 chứa một khóa không tìm thấy trong các tên trường, tham số phụ thuộc 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', '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, giá trị mặc định,
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
0 sẽ được nâng lên. Nếu nó được đặt thành
import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
1, 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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1.

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
2, tham số tên trường của lớp
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
3 không phải là tùy chọ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'})
Lớp ________ 25 ________ 76¶

Lớp

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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.
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
9 Các trường hợp xác định cách thức hoạt động của
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
0 và ____21.

Tất cả các tên
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
0 và
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1 cụ thể thông qua các hàm khởi đầu (
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 ...
5) như thế này:

import csv

with open('students.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect='unix')
                                 ^^^^^^^^^^^^^^
Lớp ________ 25 ________ 87¶

Lớp
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 ...
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ữ
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 ...
9.

Lớp ________ 25 ________ 91¶

Lớp

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
2 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('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
3.

Lớp ________ 25 ________ 95¶

Lớp

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
6 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('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
7 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('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
8.

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

Lớp ________ 25 ________ 100¶(sample, delimiters=None)

Lớp

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
01 được sử dụng để suy ra định dạng của tệp CSV.

Lớp

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
01 cung cấp hai phương pháp:

  • ________ 103 (mẫu, dấu phân cách = không) ¶

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

    python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
    
    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ề

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
05 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í,

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
05 sẽ được trả về.

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

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
01 Sử dụng:

Mô -đun
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
8 xác định các hằng số sau:

________ 25 ________ 110¶

Hướng dẫn các đối tượng
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1 để trích dẫn tất cả các trường.

________ 25 ________ 113¶

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1 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.

________ 25 ________ 116¶

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1 để trích dẫn tất cả các trường không phải là số.

Hướng dẫn

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
0 không thực hiện không xử lý đặc biệt các ký tự trích dẫn.

Mô -đun

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
8 xác định ngoại lệ sau:

Ngoại lệ ________ 25 ________ 125¶

Đượ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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
9 có một tập hợp các phương thức cụ thể và một phương thức
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
27 duy nhất. Khi tạo các đối tượng
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
0 hoặc
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1, 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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
9.

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

________ 132 ________ 133¶

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
34.

________ 132 ________ 136¶

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
05, nhân vật được nhân đôi. Khi
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
38, Escapechar được sử dụng làm tiền tố cho quotechar. Nó mặc định là
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
05.

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
38 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'])
6 sẽ được nâng lên nếu tìm thấy một quotechar trong một trường.

________ 132 ________ 143¶

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
44 và quotechar nếu doublequote là
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
38. 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
8, vô hiệu hóa việc thoát ra.

________ 132 ________ 148¶

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
1. Nó mặc định là
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
50.

Ghi chú

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
0 được mã hóa cứng để nhận ra
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
52 hoặc
import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
7 là cuối dòng và bỏ qua lineterminator. Hành vi này có thể thay đổi trong tương lai.

________ 132 ________ 155¶

Một chuỗi một ký tự được sử dụng để trích dẫn các trường chứa các ký tự đặc biệt, chẳng hạn như DELIMITER hoặc QUOTERCHAR hoặc có chứa các ký tự dòng mới. Nó mặc định là

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
56.

________ 132 ________ 158¶

Kiểm soát khi báo giá nên được tạo bởi người viết và được người đọc công nhận. Nó có thể đảm nhận bất kỳ hằng số

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
59 nào (xem nội dung mô -đun phần) và mặc định là
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
60.Module Contents) and defaults to
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
60.

________ 132 ________ 162¶

Khi

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
05, khoảng trắng ngay lập tức theo dấu phân cách bị bỏ qua. Mặc định là
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
38.

________ 132 ________ 166¶

Khi

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
05, tăng ngoại lệ
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'])
6 trên đầu vào CSV xấu. Mặc định là
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
38.

Đối tượng đọc

Đối tượng đọc (

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
2 và các đối tượng được trả về bởi hàm
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
71) có các phương thức công khai sau:

________ 172 ________ 173 ()()

Trả về hàng tiếp theo của người đọc đối tượng có thể lặp lại dưới dạng danh sách (nếu đối tượng được trả về từ

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
71) hoặc một dict (nếu đó là một thể hiện
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
2), được phân tích cú pháp theo
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
9 hiện tại. Thông thường bạn nên gọi đây là
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
77.

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

________ 172 ________ 179¶

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.

________ 172 ________ 181¶

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:

________ 172 ________ 183¶

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
84 Đối tượng (
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
3 Các trường hợp và đối tượng được trả về bởi hàm
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
86) 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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
84 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', '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 trước tiên) cho các đối tượng
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
3. 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).

________ 190 ________ 191 (hàng) ¶(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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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.

________ 190 ________ 194 (hàng) ¶(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:

________ 190 ________ 179¶

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
97 đượ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ế:

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
0

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

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
1

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
98 đượ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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
99). Để 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ố
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
00 của Open:

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
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:

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
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:

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
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:

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file output_file.csv
5

Chú thích

1(1,2)(1,2)

Nếu

python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
02 khi viết thêm
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
03 sẽ được thêm vào. Luôn luôn an toàn khi chỉ định
python3 script.py file1.csv file2.csv some_common_header_to_sort_each_file "x y z..." output_file.csv
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.

Nếu bạn đã cài đặt Microsoft Excel, chỉ cần nhấp đúp vào tệp CSV để mở nó trong Excel. Sau khi nhấp đúp vào tệp, bạn có thể thấy lời nhắc hỏi bạn muốn mở chương trình nào. Chọn Microsoft Excel. Nếu bạn đã ở Microsoft Excel, bạn có thể chọn Tệp> Mở và chọn tệp CSV.double-click a CSV file to open it in Excel. After double-clicking the file, you may see a prompt asking which program you want to open it with. Select Microsoft Excel. If you are already in Microsoft Excel, you can choose File > Open and select the CSV file.

Đầu tiên, bạn cần chụp toàn bộ đường dẫn nơi tệp CSV của bạn được lưu trữ. Bạn sẽ cần sửa đổi mã Python bên dưới để phản ánh đường dẫn lưu trữ tệp CSV trên máy tính của bạn. Đừng quên bao gồm các mục sau: Tên tệp (là máy khách).you need to capture the full path where your CSV file is stored. You'll need to modify the Python code below to reflect the path where the CSV file is stored on your computer. Don't forget to include the following: File name (as clients).

Đọc các tệp CSV với CSV Đọc từ tệp CSV được thực hiện bằng cách sử dụng đối tượng đầu đọc. Tệp CSV được mở dưới dạng tệp văn bản với hàm Open in () tích hợp của Python, trả về một đối tượng tệp.open() function, which returns a file object.