Hướng dẫn how does csv work in python? - csv hoạt động như thế nào trong python?

Xem bây giờ hướng dẫn này có một khóa học video liên quan được tạo bởi nhóm Python thực sự. Xem cùng với hướng dẫn bằng văn bản để hiểu sâu hơn về sự hiểu biết của bạn: Đọc và viết các tệp CSV This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Reading and Writing CSV Files

Show

Hãy để đối mặt với nó: Bạn cần phải có được thông tin vào và ra khỏi các chương trình của mình thông qua nhiều hơn chỉ là bàn phím và bảng điều khiển. Trao đổi thông tin thông qua các tệp văn bản là một cách phổ biến để chia sẻ thông tin giữa các chương trình. Một trong những định dạng phổ biến nhất để trao đổi dữ liệu là định dạng CSV. Nhưng làm thế nào để bạn sử dụng nó?

Hãy để một điều rõ ràng: bạn không phải (và bạn đã thắng) xây dựng trình phân tích cú pháp CSV của riêng bạn từ đầu. Có một số thư viện hoàn toàn chấp nhận được bạn có thể sử dụng. Thư viện Python

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
5 sẽ hoạt động cho hầu hết các trường hợp. Nếu công việc của bạn yêu cầu nhiều dữ liệu hoặc phân tích số, thư viện
import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6 cũng có khả năng phân tích cú pháp CSV, nên xử lý phần còn lại.

Trong bài viết này, bạn sẽ học cách đọc, xử lý và phân tích CSV từ các tệp văn bản bằng Python. Bạn sẽ thấy cách thức hoạt động của các tệp CSV, tìm hiểu thư viện

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
5 quan trọng được tích hợp vào Python và xem cách phân tích cú pháp CSV hoạt động bằng thư viện
import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6.

Vậy hãy bắt đầu!

Tệp CSV là gì?

Tệp CSV (tệp giá trị phân tách bằng dấu phẩy) là một loại tệp văn bản thuần túy sử dụng cấu trúc cụ thể để sắp xếp dữ liệu bảng. Bởi vì nó là một tệp văn bản đơn giản, nó chỉ có thể chứa dữ liệu văn bản thực tế nói cách khác, có thể in các ký tự ASCII hoặc Unicode.

Cấu trúc của một tệp CSV được đưa ra bằng tên của nó. Thông thường, các tệp CSV sử dụng dấu phẩy để phân tách từng giá trị dữ liệu cụ thể. Ở đây, cấu trúc đó trông như thế nào:

column 1 name,column 2 name, column 3 name
first row data 1,first row data 2,first row data 3
second row data 1,second row data 2,second row data 3
...

Lưu ý cách mỗi phần dữ liệu được phân tách bằng dấu phẩy. Thông thường, dòng đầu tiên xác định từng phần dữ liệu, nói cách khác, tên của một cột dữ liệu. Mỗi dòng tiếp theo sau đó là dữ liệu thực tế và chỉ bị giới hạn bởi các ràng buộc kích thước tệp.

Nói chung, ký tự phân tách được gọi là dấu phân cách và dấu phẩy không phải là người duy nhất được sử dụng. Các phân định phổ biến khác bao gồm các ký tự Tab (

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
9), Đại tràng (
Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
0) và Semi-Colon (
Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
1). Phân tích đúng tệp CSV yêu cầu chúng tôi biết dấu phân cách nào đang được sử dụng.

Các tệp CSV đến từ đâu?

Các tệp CSV thường được tạo bởi các chương trình xử lý một lượng lớn dữ liệu. Chúng là một cách thuận tiện để xuất dữ liệu từ bảng tính và cơ sở dữ liệu cũng như nhập hoặc sử dụng nó trong các chương trình khác. Ví dụ: bạn có thể xuất kết quả của chương trình khai thác dữ liệu sang tệp CSV và sau đó nhập nó vào bảng tính để phân tích dữ liệu, tạo biểu đồ cho bản trình bày hoặc chuẩn bị báo cáo để xuất bản.

Các tệp CSV rất dễ làm việc với chương trình. Bất kỳ ngôn ngữ nào hỗ trợ đầu vào tệp văn bản và thao tác chuỗi (như Python) có thể hoạt động trực tiếp với các tệp CSV.

Phân tích các tệp CSV với thư viện CSV tích hợp Python

Thư viện

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
5 cung cấp chức năng cho cả đọc và ghi vào các tệp CSV. Được thiết kế để hoạt động ngoài hộp với các tệp CSV do Excel tạo, nó dễ dàng điều chỉnh để hoạt động với nhiều định dạng CSV khác nhau. Thư viện
import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
5 chứa các đối tượng và mã khác để đọc, ghi và xử lý dữ liệu từ và đến các tệp CSV.

Đọc các tệp CSV với import csv with open('employee_birthday.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') line_count += 1 print(f'Processed {line_count} lines.') 5

Đọc từ tệp CSV được thực hiện bằng đối tượng

Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
5. Tệp CSV được mở dưới dạng tệp văn bản với chức năng
Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
6 tích hợp của Python, trả về một đối tượng tệp. Điều này sau đó được chuyển cho
Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
5, nơi thực hiện công việc nặng nhọc.

Tại đây, tệp

Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
8:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March

Đây là mã để đọc nó:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')

Điều này dẫn đến đầu ra sau:

Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.

Mỗi hàng được trả về bởi

Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
5 là danh sách các phần tử
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
0 chứa dữ liệu được tìm thấy bằng cách loại bỏ các dấu phân cách. Hàng đầu tiên được trả về chứa các tên cột, được xử lý theo một cách đặc biệt.

Đọc các tệp CSV thành một từ điển với import csv with open('employee_birthday.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') line_count += 1 print(f'Processed {line_count} lines.') 5

Thay vì xử lý một danh sách các yếu tố

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
0 riêng lẻ, bạn có thể đọc dữ liệu CSV trực tiếp vào một từ điển (về mặt kỹ thuật, từ điển được đặt hàng).

Một lần nữa, tệp đầu vào của chúng tôi,

Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
8 như sau:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March

Tại đây, mã để đọc nó như một từ điển lần này:

import csv

with open('employee_birthday.txt', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
        line_count += 1
    print(f'Processed {line_count} lines.')

Điều này dẫn đến cùng một đầu ra như trước:

Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.

Các phím từ điển đến từ đâu? Dòng đầu tiên của tệp CSV được giả sử chứa các khóa để sử dụng để xây dựng từ điển. Nếu bạn không có những thứ này trong tệp CSV của mình, bạn nên chỉ định các khóa của riêng mình bằng cách đặt tham số tùy chọn

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
4 vào danh sách chứa chúng.

Tùy chọn Python CSV Column names are name, department, birthday month John Smith works in the Accounting department, and was born in November. Erica Meyers works in the IT department, and was born in March. Processed 3 lines. 5 tham số

Đối tượng

Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
5 có thể xử lý các kiểu khác nhau của các tệp CSV bằng cách chỉ định các tham số bổ sung, một số trong đó được hiển thị bên dưới:

  • name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    7 Chỉ định ký tự được sử dụng để tách từng trường. Mặc định là dấu phẩy (
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    8).

  • name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    9 Chỉ định ký tự được sử dụng để bao quanh các trường chứa ký tự phân cách. Mặc định là một báo giá kép (
    import csv
    
    with open('employee_birthday.txt', mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
            line_count += 1
        print(f'Processed {line_count} lines.')
    
    0).

  • import csv
    
    with open('employee_birthday.txt', mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
            line_count += 1
        print(f'Processed {line_count} lines.')
    
    1 Chỉ định ký tự được sử dụng để thoát khỏi ký tự phân cách, trong trường hợp trích dẫn aren được sử dụng. Mặc định là không có ký tự thoát.

Những thông số này xứng đáng được giải thích thêm. Giả sử bạn làm việc với tệp

import csv

with open('employee_birthday.txt', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
        line_count += 1
    print(f'Processed {line_count} lines.')
2 sau:

name,address,date joined
john smith,1132 Anywhere Lane Hoboken NJ, 07030,Jan 4
erica meyers,1234 Smith Lane Hoboken NJ, 07030,March 2

Tệp CSV này chứa ba trường:

import csv

with open('employee_birthday.txt', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
        line_count += 1
    print(f'Processed {line_count} lines.')
3,
import csv

with open('employee_birthday.txt', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
        line_count += 1
    print(f'Processed {line_count} lines.')
4 và
import csv

with open('employee_birthday.txt', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
        line_count += 1
    print(f'Processed {line_count} lines.')
5, được phân định bởi dấu phẩy. Vấn đề là dữ liệu cho trường
import csv

with open('employee_birthday.txt', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
        line_count += 1
    print(f'Processed {line_count} lines.')
4 cũng chứa dấu phẩy để biểu thị mã zip.

Có ba cách khác nhau để xử lý tình huống này:

  • Sử dụng một dấu phân cách khác theo cách đó, dấu phẩy có thể được sử dụng một cách an toàn trong chính dữ liệu. Bạn sử dụng tham số tùy chọn

    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    7 để chỉ định trình phân cách mới.
    That way, the comma can safely be used in the data itself. You use the
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    7 optional parameter to specify the new delimiter.

  • Bao bọc dữ liệu trong trích dẫn Bản chất đặc biệt của Delimiter đã chọn của bạn bị bỏ qua trong các chuỗi được trích dẫn. Do đó, bạn có thể chỉ định ký tự được sử dụng để trích dẫn với tham số tùy chọn

    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    9. Miễn là nhân vật đó cũng không xuất hiện trong dữ liệu, bạn sẽ ổn.
    The special nature of your chosen delimiter is ignored in quoted strings. Therefore, you can specify the character used for quoting with the
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    9 optional parameter. As long as that character also doesn’t appear in the data, you’re fine.

  • Thoát khỏi các ký tự phân cách trong các ký tự thoát dữ liệu hoạt động giống như chúng trong các chuỗi định dạng, vô hiệu hóa việc giải thích nhân vật bị thoát ra (trong trường hợp này là dấu phân cách). Nếu một ký tự thoát được sử dụng, nó phải được chỉ định bằng tham số tùy chọn

    import csv
    
    with open('employee_birthday.txt', mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
            line_count += 1
        print(f'Processed {line_count} lines.')
    
    1.
    Escape characters work just as they do in format strings, nullifying the interpretation of the character being escaped (in this case, the delimiter). If an escape character is used, it must be specified using the
    import csv
    
    with open('employee_birthday.txt', mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
            line_count += 1
        print(f'Processed {line_count} lines.')
    
    1 optional parameter.

Viết các tệp CSV bằng import csv with open('employee_birthday.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') line_count += 1 print(f'Processed {line_count} lines.') 5

Bạn cũng có thể ghi vào tệp CSV bằng đối tượng

Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
1 và phương thức
Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
2:

import csv

with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    employee_writer.writerow(['John Smith', 'Accounting', 'November'])
    employee_writer.writerow(['Erica Meyers', 'IT', 'March'])

Tham số tùy chọn

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
9 cho biết
Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
1 nhân vật nào sẽ sử dụng để trích dẫn các trường khi viết. Tuy nhiên, việc trích dẫn có được sử dụng hay không được xác định bởi tham số tùy chọn
Column names are name, department, birthday month
    John Smith works in the Accounting department, and was born in November.
    Erica Meyers works in the IT department, and was born in March.
Processed 3 lines.
5:

  • Nếu
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    5 được đặt thành
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    7, thì
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    8 sẽ chỉ trích dẫn các trường nếu chúng chứa
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    7 hoặc
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    9. Đây là trường hợp mặc định.
  • Nếu
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    5 được đặt thành
    name,address,date joined
    john smith,1132 Anywhere Lane Hoboken NJ, 07030,Jan 4
    erica meyers,1234 Smith Lane Hoboken NJ, 07030,March 2
    
    
    2, thì
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    8 sẽ báo giá tất cả các trường.
  • Nếu
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    5 được đặt thành
    name,address,date joined
    john smith,1132 Anywhere Lane Hoboken NJ, 07030,Jan 4
    erica meyers,1234 Smith Lane Hoboken NJ, 07030,March 2
    
    
    5, thì
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    8 sẽ trích dẫn tất cả các trường chứa dữ liệu văn bản và chuyển đổi tất cả các trường số thành loại dữ liệu
    name,address,date joined
    john smith,1132 Anywhere Lane Hoboken NJ, 07030,Jan 4
    erica meyers,1234 Smith Lane Hoboken NJ, 07030,March 2
    
    
    7.
  • Nếu
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    5 được đặt thành
    name,address,date joined
    john smith,1132 Anywhere Lane Hoboken NJ, 07030,Jan 4
    erica meyers,1234 Smith Lane Hoboken NJ, 07030,March 2
    
    
    9, thì
    Column names are name, department, birthday month
        John Smith works in the Accounting department, and was born in November.
        Erica Meyers works in the IT department, and was born in March.
    Processed 3 lines.
    
    8 sẽ thoát khỏi các phân định thay vì trích dẫn chúng. Trong trường hợp này, bạn cũng phải cung cấp một giá trị cho tham số tùy chọn
    import csv
    
    with open('employee_birthday.txt', mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
            line_count += 1
        print(f'Processed {line_count} lines.')
    
    1.

Đọc lại tệp trong văn bản đơn giản cho thấy tệp được tạo như sau:

John Smith,Accounting,November
Erica Meyers,IT,March

Viết tệp CSV từ một từ điển với import csv with open('employee_birthday.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') line_count += 1 print(f'Processed {line_count} lines.') 5

Vì bạn có thể đọc dữ liệu của chúng tôi vào một từ điển, nên chỉ công bằng rằng bạn cũng có thể viết nó từ một từ điển:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
0

Không giống như

import csv

with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    employee_writer.writerow(['John Smith', 'Accounting', 'November'])
    employee_writer.writerow(['Erica Meyers', 'IT', 'March'])
3, tham số
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
4 là bắt buộc khi viết từ điển. Điều này có ý nghĩa, khi bạn nghĩ về nó: Không có danh sách
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
4,
import csv

with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    employee_writer.writerow(['John Smith', 'Accounting', 'November'])
    employee_writer.writerow(['Erica Meyers', 'IT', 'March'])
6 có thể biết các khóa nào sẽ sử dụng để truy xuất các giá trị từ từ điển của bạn. Nó cũng sử dụng các phím trong
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
4 để ghi ra hàng đầu tiên dưới dạng tên cột.

Mã trên tạo tệp đầu ra sau:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
1

Phân tích các tệp CSV với thư viện import csv with open('employee_birthday.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') line_count += 1 print(f'Processed {line_count} lines.') 6

Tất nhiên, thư viện Python CSV không phải là trò chơi duy nhất trong thị trấn. Đọc các tệp CSV cũng có thể trong

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6. Rất khuyến khích nếu bạn có nhiều dữ liệu để phân tích.

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6 là một thư viện Python nguồn mở cung cấp các công cụ phân tích dữ liệu hiệu suất cao và dễ sử dụng các cấu trúc dữ liệu.
import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6 có sẵn cho tất cả các cài đặt Python, nhưng nó là một phần quan trọng của phân phối Anaconda và hoạt động rất tốt trong các máy tính xách tay Jupyter để chia sẻ dữ liệu, mã, kết quả phân tích, trực quan hóa và văn bản tường thuật.

Cài đặt

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6 và các phụ thuộc của nó trong
John Smith,Accounting,November
Erica Meyers,IT,March
3 dễ dàng thực hiện:

Như đang sử dụng ________ 94/________ 95 cho các cài đặt Python khác:

Chúng tôi đã giành chiến thắng trong các chi tiết cụ thể về cách thức hoạt động của

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6 hoặc cách sử dụng nó. Để điều trị chuyên sâu về việc sử dụng
import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6 để đọc và phân tích các bộ dữ liệu lớn, hãy xem bài viết tuyệt vời của Chaiwari Tiwari, làm việc với các tệp excel lớn trong gấu trúc.

Đọc các tệp CSV với import csv with open('employee_birthday.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') line_count += 1 print(f'Processed {line_count} lines.') 6

Để hiển thị một số sức mạnh của các khả năng CSV

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6, tôi đã tạo ra một tệp phức tạp hơn một chút để đọc, được gọi là
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
00. Nó chứa dữ liệu về nhân viên công ty:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
2

Đọc CSV thành A

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
02 rất nhanh và đơn giản:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
3

Rằng nó: ba dòng mã và chỉ một trong số chúng đang thực hiện công việc thực tế.

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
03 mở, phân tích và đọc tệp CSV được cung cấp và lưu trữ dữ liệu trong DataFrame. In kết quả
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
02 trong đầu ra sau:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
4

Dưới đây là một vài điểm đáng chú ý:

  • Đầu tiên,
    import csv
    
    with open('employee_birthday.txt') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
                line_count += 1
        print(f'Processed {line_count} lines.')
    
    6 nhận ra rằng dòng đầu tiên của CSV chứa tên cột và sử dụng chúng tự động. Tôi gọi đây là lòng tốt.
  • Tuy nhiên,
    import csv
    
    with open('employee_birthday.txt') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
                line_count += 1
        print(f'Processed {line_count} lines.')
    
    6 cũng đang sử dụng các chỉ số số nguyên dựa trên không trong
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    02. Điều đó bởi vì chúng tôi đã nói với nó những gì chỉ số của chúng tôi nên là.
  • Hơn nữa, nếu bạn nhìn vào các loại dữ liệu của các cột của chúng tôi, bạn sẽ thấy

    import csv
    
    with open('employee_birthday.txt') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
                line_count += 1
        print(f'Processed {line_count} lines.')
    
    6 đã chuyển đổi đúng các cột
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    09 và
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    10 thành các số, nhưng cột
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    11 vẫn là một
    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    0. Điều này dễ dàng được xác nhận ở chế độ tương tác:

    >>>

    name,department,birthday month
    John Smith,Accounting,November
    Erica Meyers,IT,March
    
    5

Hãy để giải quyết vấn đề này một lần. Để sử dụng một cột khác làm chỉ mục

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
02, hãy thêm tham số tùy chọn
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
14:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
6

Bây giờ trường

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
15 là chỉ mục
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
02 của chúng tôi:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
7

Tiếp theo, hãy để sửa lỗi loại dữ liệu của trường

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
11. Bạn có thể buộc
import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6 phải đọc dữ liệu như một ngày với tham số tùy chọn
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
19, được định nghĩa là danh sách các tên cột để xử lý là ngày:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
8

Lưu ý sự khác biệt trong đầu ra:

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
9

Ngày hiện được định dạng đúng, dễ dàng xác nhận ở chế độ tương tác:

>>>

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
0

Hãy để giải quyết vấn đề này một lần. Để sử dụng một cột khác làm chỉ mục

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
02, hãy thêm tham số tùy chọn
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
14:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
1

Bây giờ trường

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
15 là chỉ mục
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
02 của chúng tôi:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
2

Tiếp theo, hãy để sửa lỗi loại dữ liệu của trường name,department,birthday month John Smith,Accounting,November Erica Meyers,IT,March 11. Bạn có thể buộc import csv with open('employee_birthday.txt') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') line_count += 1 print(f'Processed {line_count} lines.') 6 phải đọc dữ liệu như một ngày với tham số tùy chọn name,department,birthday month John Smith,Accounting,November Erica Meyers,IT,March 19, được định nghĩa là danh sách các tên cột để xử lý là ngày:

Lưu ý sự khác biệt trong đầu ra:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
3

Ngày hiện được định dạng đúng, dễ dàng xác nhận ở chế độ tương tác:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
4

Nếu các tệp CSV của bạn không có tên cột trong dòng đầu tiên, bạn có thể sử dụng tham số tùy chọn name,department,birthday month John Smith,Accounting,November Erica Meyers,IT,March 20 để cung cấp danh sách các tên cột. Bạn cũng có thể sử dụng điều này nếu bạn muốn ghi đè các tên cột được cung cấp trong dòng đầu tiên. Trong trường hợp này, bạn cũng phải nói với name,department,birthday month John Smith,Accounting,November Erica Meyers,IT,March 03 để bỏ qua các tên cột hiện có bằng tham số tùy chọn name,department,birthday month John Smith,Accounting,November Erica Meyers,IT,March 22:

Lưu ý rằng, vì các tên cột đã thay đổi, các cột được chỉ định trong các tham số tùy chọn

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
14 và
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
19 cũng phải được thay đổi. Điều này bây giờ dẫn đến đầu ra sau:

Viết các tệp CSV bằng

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6

Tất nhiên, nếu bạn có thể lấy dữ liệu của mình ra khỏi

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
6 một lần nữa, thì điều đó không tốt cho bạn. Viết một
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
02 vào tệp CSV cũng dễ dàng như đọc một tệp. Hãy viết dữ liệu với tên cột mới vào tệp CSV mới:

Sự khác biệt duy nhất giữa mã này và mã đọc ở trên là cuộc gọi

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
28 đã được thay thế bằng
name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March
29, cung cấp tên tệp. Tệp CSV mới trông như thế này: This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Reading and Writing CSV Files