Nối các tệp CSV Python

Để nối thêm một hàng [=dictionary] vào CSV hiện có, hãy mở đối tượng tệp ở chế độ nối thêm bằng cách sử dụng open['my_file.csv', 'a', newline='']. Sau đó, tạo một csv.DictWriter[] để nối thêm một hàng chính tả bằng cách sử dụng DictWriter.writerow[my_dict]

Đưa ra tệp sau 'my_file.csv'

Bạn có thể nối một hàng [dict] vào tệp CSV qua đoạn mã này

import csv

# Create the dictionary [=row]
row = {'A':'Y1', 'B':'Y2', 'C':'Y3'}

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=row.keys[]]

    # Append single row to CSV
    writer.writerow[row]

Sau khi chạy mã trong cùng thư mục với 'my_file.csv' ban đầu của bạn, bạn sẽ thấy kết quả sau

Nối nhiều hàng vào CSV

Đưa ra tệp CSV sau

Để thêm nhiều hàng [i. e. , dicts] vào tệp CSV cũ hiện có, lặp qua các hàng và viết từng

import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
0 bằng cách gọi
import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
1 trên đối tượng
import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
2 được tạo ban đầu

Đây là một ví dụ [những thay đổi lớn được đánh dấu]

import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]

Tệp CSV kết quả có tất cả ba hàng được thêm vào hàng đầu tiên

Python Thêm hàng vào gấu trúc CSV

Để thêm một hàng vào CSV hiện có bằng Pandas, bạn có thể đặt đối số write

import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
3 để nối thêm
import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
4 trong phương thức
import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
5 của Pandas DataFrame như vậy.
import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
6

df.to_csv['my_csv.csv', mode='a', header=False]

Để biết ví dụ đầy đủ, hãy xem đoạn mã này

import pandas as pd

# Create the initial CSV data
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Create a DataFrame and write to CSV
df = pd.DataFrame[rows]
df.to_csv['my_file.csv', header=False, index=False]

# Create another row and append row [as df] to existing CSV
row = [{'A':'X1', 'B':'X2', 'C':'X3'}]
df = pd.DataFrame[row]
df.to_csv['my_file.csv', mode='a', header=False, index=False]

Tệp đầu ra trông như thế này [hàng mới được đánh dấu]

Ngoài ra, bạn có thể mở tệp ở chế độ nối thêm bằng cách sử dụng hàm

import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
7 bình thường với đối số nối thêm
import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
4 và chuyển nó vào phương thức
import csv

# Create the dictionary [=row]
rows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'},
        {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'},
        {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}]

# Open the CSV file in "append" mode
with open['my_file.csv', 'a', newline=''] as f:

    # Create a dictionary writer with the dict keys as column fieldnames
    writer = csv.DictWriter[f, fieldnames=rows[0].keys[]]

    # Append multiple rows to CSV
    for row in rows:
        writer.writerow[row]
9 của DataFrame

Đây là một đoạn ví dụ để sao chép dán

with open['my_csv.csv', 'a'] as f:
    df.to_csv[f, header=False]

🌍 Tìm hiểu thêm. Nếu bạn muốn tìm hiểu về 7 cách tốt nhất để chuyển đổi Dict sang CSV bằng Python, hãy xem hướng dẫn Finxter này

Chris

Trong khi làm việc với tư cách là một nhà nghiên cứu trong các hệ thống phân tán, Dr. Christian Mayer tìm thấy tình yêu của mình với việc dạy sinh viên khoa học máy tính

Để giúp sinh viên đạt được mức độ thành công Python cao hơn, anh ấy đã thành lập trang web giáo dục lập trình Finxter. com. Ông là tác giả của cuốn sách lập trình nổi tiếng Python One-Liners [NoStarch 2020], đồng tác giả của loạt sách tự xuất bản Coffee Break Python, người đam mê khoa học máy tính, cộng tác viên tự do và chủ sở hữu của một trong 10 blog Python lớn nhất thế giới

Niềm đam mê của anh ấy là viết, đọc và mã hóa. Nhưng niềm đam mê lớn nhất của anh ấy là phục vụ các lập trình viên đầy tham vọng thông qua Finxter và giúp họ nâng cao kỹ năng của mình. Bạn có thể tham gia học viện email miễn phí của anh ấy tại đây

Làm cách nào để kết hợp 2 tệp CSV?

Để kết hợp nhiều tệp csv vào một sổ làm việc Excel, đây là các bước bạn cần thực hiện. .
Đặt tất cả các tệp CSV của bạn vào một thư mục. .
Trên tab Dữ liệu, trong nhóm Lấy & Chuyển đổi Dữ liệu, bấm Lấy Dữ liệu > Từ Tệp > Từ Thư mục
Duyệt tìm thư mục mà bạn đã đặt các tệp csv và nhấp vào Mở

Làm cách nào để kết hợp nhiều tệp văn bản thành một CSV bằng Python?

Nếu tất cả các tệp có cùng cấu trúc bảng [cùng tiêu đề & số cột], hãy để tập lệnh Python nhỏ này thực hiện công việc. .
Bước 1. Nhập gói và đặt thư mục làm việc. .
Bước 2. Sử dụng toàn cầu để khớp với mẫu 'csv'.
Bước 3. Kết hợp tất cả các tệp trong danh sách và xuất dưới dạng CSV

Làm cách nào để thêm CSV vào Python?

Các bước để nhập tệp CSV vào Python bằng Pandas .
Bước 1. Nắm bắt đường dẫn tệp. Đầu tiên, nắm bắt đường dẫn đầy đủ nơi tệp CSV của bạn được lưu trữ. .
Bước 2. Áp dụng mã Python. .
Bước 3. Chạy mã. .
Bước tùy chọn. Chọn tập hợp con của các cột

Chủ Đề