Hướng dẫn python csv write header once - python csv ghi tiêu đề một lần

Dưới đây là một ví dụ khác chỉ phụ thuộc vào gói


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

2 của Python. Phương pháp này kiểm tra xem tiêu đề là những gì được mong đợi hay nó gây ra lỗi. Nó cũng xử lý trường hợp tệp không tồn tại hoặc không tồn tại nhưng trống bằng cách viết tiêu đề. Hi vọng điêu nay co ich:

import csv
import os


def append_to_csv(path, fieldnames, rows):
    is_write_header = not os.path.exists(path) or _is_empty_file(path)
    if not is_write_header:
        _assert_field_names_match(path, fieldnames)

    _append_to_csv(path, fieldnames, rows, is_write_header)


def _is_empty_file(path):
    return os.stat(path).st_size == 0


def _assert_field_names_match(path, fieldnames):
    with open(path, 'r') as f:
        reader = csv.reader(f)
        header = next(reader)
        if header != fieldnames:
            raise ValueError(f'Incompatible header: expected {fieldnames}, '
                             f'but existing file has {header}')


def _append_to_csv(path, fieldnames, rows, is_write_header: bool):
    with open(path, 'a') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        if is_write_header:
            writer.writeheader()
        writer.writerows(rows)

Bạn có thể kiểm tra điều này với mã sau:


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

Nếu bạn chạy điều này sau khi bạn nhận được những điều sau trong


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

3:

name,area,country_code2,country_code3
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM

Và nếu bạn chạy nó hai lần, bạn sẽ nhận được những điều sau (lưu ý, không có tiêu đề thứ hai):

name,area,country_code2,country_code3
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM

Nếu sau đó bạn thay đổi tiêu đề trong


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

3 và chạy lại chương trình, bạn sẽ gặp lỗi giá trị, như thế này:

ValueError: Incompatible header: expected ['name', 'area', 'country_code2', 'country_code3'], but existing file has ['not', 'right', 'fieldnames']

Tóm tắt: Trong hướng dẫn này, bạn sẽ học cách ghi dữ liệu vào tệp CSV bằng mô-đun


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

2 tích hợp.: in this tutorial, you’ll learn how to write data into a CSV file using the built-in

file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

2 module.

Các bước để viết tệp CSV

Để ghi dữ liệu vào tệp CSV, bạn làm theo các bước sau:

  • Đầu tiên, hãy mở tệp CSV để viết (chế độ
    
    file_ = 'countries.csv'
    fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
    rows_ = [
        {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
        {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
        {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
    ]
    
    append_to_csv(file_, fieldnames_, rows_)
    
    
    6) bằng cách sử dụng hàm
    
    file_ = 'countries.csv'
    fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
    rows_ = [
        {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
        {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
        {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
    ]
    
    append_to_csv(file_, fieldnames_, rows_)
    
    
    7.
  • Thứ hai, tạo đối tượng người viết CSV bằng cách gọi hàm
    
    file_ = 'countries.csv'
    fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
    rows_ = [
        {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
        {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
        {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
    ]
    
    append_to_csv(file_, fieldnames_, rows_)
    
    
    8 của mô -đun
    
    file_ = 'countries.csv'
    fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
    rows_ = [
        {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
        {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
        {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
    ]
    
    append_to_csv(file_, fieldnames_, rows_)
    
    
    2.
  • Thứ ba, ghi dữ liệu vào tệp CSV bằng cách gọi phương thức
    name,area,country_code2,country_code3
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    
    0 hoặc
    name,area,country_code2,country_code3
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    
    1 của đối tượng người viết CSV.
  • Cuối cùng, đóng tệp sau khi bạn hoàn thành việc viết dữ liệu cho nó.

Mã sau đây minh họa các bước trên:

import csv # open the file in the write mode f = open('path/to/csv_file', 'w') # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row) # close the file f.close()

Code language: Python (python)

Nó sẽ ngắn hơn nếu bạn sử dụng câu lệnh

name,area,country_code2,country_code3
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM
2 để bạn không cần gọi phương thức
name,area,country_code2,country_code3
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM
3 để đóng tệp một cách rõ ràng:

import csv # open the file in the write mode with open('path/to/csv_file', 'w') as f: # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row)

Code language: PHP (php)

Nếu bạn xử lý các ký tự không phải ASCII, bạn cần chỉ định mã hóa ký tự trong hàm


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

7.

Sau đây minh họa cách viết các ký tự UTF-8 vào tệp CSV:

import csv # open the file in the write mode with open('path/to/csv_file', 'w', encoding='UTF8') as f: # create the csv writer writer = csv.writer(f) # write a row to the csv file writer.writerow(row)

Code language: PHP (php)

Viết vào ví dụ về tệp CSV

Ví dụ sau đây cho thấy cách ghi dữ liệu vào tệp CSV:

import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = ['Afghanistan', 652090, 'AF', 'AFG'] with open('countries.csv', 'w', encoding='UTF8') as f: writer = csv.writer(f) # write the header writer.writerow(header) # write the data writer.writerow(data)

Code language: PHP (php)

Nếu bạn mở


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

3, bạn sẽ thấy một vấn đề rằng nội dung tệp có thêm dòng trống giữa hai hàng tiếp theo:

Hướng dẫn python csv write header once - python csv ghi tiêu đề một lần

Để xóa dòng trống, bạn chuyển đối số từ khóa

name,area,country_code2,country_code3
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM
6 cho hàm

file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

7 như sau:

import csv header = ['name', 'area', 'country_code2', 'country_code3'] data = ['Afghanistan', 652090, 'AF', 'AFG'] with open('countries.csv', 'w', encoding='UTF8', newline='') as f: writer = csv.writer(f) # write the header writer.writerow(header) # write the data writer.writerow(data)

Code language: PHP (php)

Output:

Hướng dẫn python csv write header once - python csv ghi tiêu đề một lần

Viết nhiều hàng vào các tệp CSV

Để ghi nhiều hàng vào tệp CSV cùng một lúc, bạn sử dụng phương thức

name,area,country_code2,country_code3
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM
1 của đối tượng người viết CSV.

Sau đây sử dụng phương thức

name,area,country_code2,country_code3
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM
1 để ghi nhiều hàng vào tệp

file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

3:


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

0

Ghi vào các tệp CSV bằng lớp DictWriter

Nếu mỗi hàng của tệp CSV là từ điển, bạn có thể sử dụng lớp

name,area,country_code2,country_code3
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM
Albania,28748,AL,ALB
Algeria,2381741,DZ,DZA
American Samoa,199,AS,ASM
1 của mô -đun

file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

2 để viết từ điển vào tệp CSV.

Ví dụ minh họa cách sử dụng lớp DictWriter để ghi dữ liệu vào tệp CSV:


file_ = 'countries.csv'
fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
rows_ = [
    {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
    {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
    {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
]

append_to_csv(file_, fieldnames_, rows_)

1

Làm thế nào nó hoạt động.

  • Đầu tiên, xác định các biến giữ tên trường và hàng dữ liệu của tệp CSV.
  • Tiếp theo, mở tệp CSV để viết bằng cách gọi hàm
    
    file_ = 'countries.csv'
    fieldnames_ = ['name', 'area', 'country_code2', 'country_code3']
    rows_ = [
        {'name': 'Albania', 'area': 28748, 'country_code2': 'AL', 'country_code3': 'ALB'},
        {'name': 'Algeria', 'area': 2381741, 'country_code2': 'DZ', 'country_code3': 'DZA'},
        {'name': 'American Samoa', 'area': 199, 'country_code2': 'AS', 'country_code3': 'ASM'}
    ]
    
    append_to_csv(file_, fieldnames_, rows_)
    
    
    7.
  • Sau đó, tạo một thể hiện mới của lớp
    name,area,country_code2,country_code3
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    
    1 bằng cách chuyển đối tượng tệp (
    name,area,country_code2,country_code3
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    
    5) và đối số
    name,area,country_code2,country_code3
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    
    6 cho nó.
  • Sau đó, hãy viết tiêu đề cho tệp CSV bằng cách gọi phương thức
    name,area,country_code2,country_code3
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    
    7.
  • Cuối cùng, ghi các hàng dữ liệu vào tệp CSV bằng phương thức
    name,area,country_code2,country_code3
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    
    1.

Bản tóm tắt

  • Sử dụng người viết CSV hoặc lớp
    name,area,country_code2,country_code3
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    Albania,28748,AL,ALB
    Algeria,2381741,DZ,DZA
    American Samoa,199,AS,ASM
    
    1 để ghi dữ liệu vào tệp CSV.

Bạn có thấy hướng dẫn này hữu ích không?

Làm cách nào để làm cho hàng đầu tiên thành tiêu đề trong CSV?

Trong khung truy vấn, chọn Chỉnh sửa để mở Trình chỉnh sửa truy vấn Power.Để xác nhận rằng Truy vấn Power đã nhận ra các tiêu đề của bạn ở hàng trên cùng, chọn Home> Transform, sau đó chọn Sử dụng hàng đầu tiên làm tiêu đề.Truy vấn Power chuyển đổi hàng dữ liệu đầu tiên thành hàng tiêu đề.select Home > Transform, and then select Use first row as headers. Power Query converts the first row of data to a header row.

Làm cách nào để thêm tiêu đề vào tệp CSV?

Cách thực hiện một hàng tiêu đề trong tệp CSV..
Nhấp chuột phải vào biểu tượng cho tệp CSV và di chuyển chuột của bạn lên "Mở cùng."....
Chọn WordPad hoặc Notepad từ danh sách.....
Nhấp vào bất cứ nơi nào trong văn bản mở ra và nhấn "ctrl+home" để di chuyển con trỏ sang không gian đầu tiên trong hộp văn bản ..

Làm thế nào để tôi thực hiện một tiêu đề trong Python?

Làm thế nào để tôi thực hiện một tiêu đề trong Python?Bạn có thể tạo các tiêu đề bằng cách bắt đầu và kết thúc một dòng với tối đa năm dấu hiệu bằng nhau.Văn bản tiêu đề là giữa các điểm đánh dấu, cách nhau bởi một không gian duy nhất.starting and ending a line with up to five equal signs. The heading text is between those markers, separated by a single space.