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
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_]
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ế độ
6] bằng cách sử dụng hàmfile_ = '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.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_]
- Thứ hai, tạo đối tượng người viết CSV bằng cách gọi hàm
8 của mô -đunfile_ = '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.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_]
- Thứ ba, ghi dữ liệu vào tệp CSV bằng cách gọi phương thức
0 hoặcname,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.name,area,country_code2,country_code3 Albania,28748,AL,ALB Algeria,2381741,DZ,DZA American Samoa,199,AS,ASM
- 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:
Code language: Python [python]
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[]
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:Code language: PHP [php]
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]
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:
Code language: PHP [php]
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]
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:
Code language: PHP [php]
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]
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:Để 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:Code language: PHP [php]
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]
Output:
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_]
0Ghi 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_]
1Là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
7.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_]
- Sau đó, tạo một thể hiện mới của lớp
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ó.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
- Sau đó, hãy viết tiêu đề cho tệp CSV bằng cách gọi phương thức
7.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
- Cuối cùng, ghi các hàng dữ liệu vào tệp CSV bằng phương thức
1.name,area,country_code2,country_code3 Albania,28748,AL,ALB Algeria,2381741,DZ,DZA American Samoa,199,AS,ASM
Bản tóm tắt
- Sử dụng người viết CSV hoặc lớp
1 để ghi dữ liệu vào tệp CSV.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
Bạn có thấy hướng dẫn này hữu ích không?