Python CSV: Đọc và ghi tệp CSV

Trong hướng dẫn này, chúng ta sẽ học cách đọc và ghi vào tệp CSV bằng Python với sự trợ giúp của các ví dụ.

Định dạng CSV (Giá trị được phân tách bằng dấu phẩy) là một trong những cách đơn giản và phổ biến nhất để lưu trữ dữ liệu dạng bảng. Để đại diện cho một tệp CSV, nó phải được lưu với phần mở rộng tệp .csv .

Hãy lấy một ví dụ:

Nếu bạn mở tệp CSV ở trên bằng trình chỉnh sửa văn bản, chẳng hạn như văn bản siêu phàm, bạn sẽ thấy:

 SN, Tên, Thành phố 1, Michael, New Jersey 2, Jack, California 

Như bạn có thể thấy, các phần tử của tệp CSV được phân tách bằng dấu phẩy. Đây, ,là một dấu phân cách.

Bạn có thể có bất kỳ ký tự đơn nào làm dấu phân cách tùy theo nhu cầu của bạn.

Lưu ý: Mô-đun csv cũng có thể được sử dụng cho các phần mở rộng tệp khác (như: .txt ) miễn là nội dung của chúng có cấu trúc phù hợp.

Làm việc với tệp CSV bằng Python

Mặc dù chúng tôi có thể sử dụng open()hàm tích hợp để làm việc với các tệp CSV bằng Python, nhưng có một csvmô-đun chuyên dụng giúp làm việc với các tệp CSV dễ dàng hơn nhiều.

Trước khi có thể sử dụng các phương thức cho csvmô-đun, trước tiên chúng tôi cần nhập mô-đun bằng cách sử dụng:

 import csv 

Đọc tệp CSV bằng csv.reader ()

Để đọc tệp CSV bằng Python, chúng ta có thể sử dụng csv.reader()hàm. Giả sử chúng ta có một csvtệp tên là people.csv trong thư mục hiện tại với các mục sau.

Tên Tuổi tác Nghề nghiệp
Jack 23 Bác sĩ
Miller 22 Kỹ sư

Hãy đọc tệp này bằng cách sử dụng csv.reader():

Ví dụ 1: Đọc CSV có dấu phân cách bằng dấu phẩy

 import csv with open('people.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) 

Đầu ra

 ('Tên', 'Tuổi', 'Nghề nghiệp') ('Jack', '23', 'Bác sĩ') ('Miller', '22', 'Kỹ sư') 

Ở đây, chúng tôi đã mở tệp people.csv ở chế độ đọc bằng cách sử dụng:

 with open('people.csv', 'r') as file:… 

Để tìm hiểu thêm về cách mở tệp bằng Python, hãy truy cập: Đầu vào / đầu ra tệp Python

Sau đó, hàm csv.reader()được sử dụng để đọc tệp, tệp này trả về một readerđối tượng có thể lặp lại .

Đối readertượng sau đó được lặp lại bằng cách sử dụng một forvòng lặp để in nội dung của mỗi hàng.

Trong ví dụ trên, chúng tôi đang sử dụng csv.reader()hàm ở chế độ mặc định cho các tệp CSV có dấu phân cách bằng dấu phẩy.

Tuy nhiên, chức năng có thể tùy biến nhiều hơn.

Giả sử tệp CSV của chúng tôi đang sử dụng tab làm dấu phân cách. Để đọc các tệp như vậy, chúng ta có thể chuyển các tham số tùy chọn cho csv.reader()hàm. Hãy lấy một ví dụ.

Ví dụ 2: Đọc tệp CSV có Dấu phân cách tab

 import csv with open('people.csv', 'r',) as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row) 

Lưu ý tham số tùy chọn delimiter = ' 'trong ví dụ trên.

Cú pháp hoàn chỉnh của csv.reader()hàm là:

 csv.reader(csvfile, dialect='excel', **optional_parameters) 

Như bạn có thể thấy từ cú pháp, chúng ta cũng có thể truyền tham số phương ngữ cho csv.reader()hàm. Các dialecttham số cho phép chúng ta thực hiện các chức năng linh hoạt hơn. Để tìm hiểu thêm, hãy truy cập: Đọc tệp CSV bằng Python.

Viết tệp CSV bằng csv.writer ()

Để ghi vào tệp CSV bằng Python, chúng ta có thể sử dụng csv.writer()hàm.

Các csv.writer()chức năng trả về một writerđối tượng mà cải dữ liệu của người dùng vào một chuỗi phân cách. Chuỗi này sau đó có thể được sử dụng để ghi vào tệp CSV bằng writerow()hàm. Hãy lấy một ví dụ.

Ví dụ 3: Ghi vào tệp CSV

 import csv with open('protagonist.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(("SN", "Movie", "Protagonist")) writer.writerow((1, "Lord of the Rings", "Frodo Baggins")) writer.writerow((2, "Harry Potter", "Harry Potter")) 

Khi chúng tôi chạy chương trình trên, một tệp prot character.csv được tạo với nội dung sau:

 SN, Phim, Nhân vật chính 1, Chúa tể của những chiếc nhẫn, Frodo Baggins 2, Harry Potter, Harry Potter 

Trong chương trình trên, chúng tôi đã mở tệp ở chế độ ghi.

Sau đó, chúng tôi đã chuyển từng hàng dưới dạng danh sách. Các danh sách này được chuyển đổi thành một chuỗi được phân tách và được ghi vào tệp CSV.

Ví dụ 4: Viết nhiều hàng bằng writerows ()

Nếu chúng ta cần ghi nội dung của danh sách 2 chiều vào tệp CSV, thì đây là cách chúng ta có thể thực hiện.

 import csv csv_rowlist = (("SN", "Movie", "Protagonist"), (1, "Lord of the Rings", "Frodo Baggins"), (2, "Harry Potter", "Harry Potter")) with open('protagonist.csv', 'w') as file: writer = csv.writer(file) writer.writerows(csv_rowlist) 

The output of the program is the same as in Example 3.

Here, our 2-dimensional list is passed to the writer.writerows() method to write the content of the list to the CSV file.

Example 5: Writing to a CSV File with Tab Delimiter

 import csv with open('protagonist.csv', 'w') as file: writer = csv.writer(file, delimiter = ' ') writer.writerow(("SN", "Movie", "Protagonist")) writer.writerow((1, "Lord of the Rings", "Frodo Baggins")) writer.writerow((2, "Harry Potter", "Harry Potter")) 

Notice the optional parameter delimiter = ' ' in the csv.writer() function.

The complete syntax of the csv.writer() function is:

 csv.writer(csvfile, dialect='excel', **optional_parameters) 

Similar to csv.reader(), you can also pass dialect parameter the csv.writer() function to make the function much more customizable. To learn more, visit: Writing CSV files in Python

Python csv.DictReader() Class

The objects of a csv.DictReader() class can be used to read a CSV file as a dictionary.

Example 6: Python csv.DictReader()

Suppose we have the same file people.csv as in Example 1.

Name Age Profession
Jack 23 Doctor
Miller 22 Engineer

Let's see how csv.DictReader() can be used.

 import csv with open("people.csv", 'r') as file: csv_file = csv.DictReader(file) for row in csv_file: print(dict(row)) 

Output

 ('Name': 'Jack', ' Age': ' 23', ' Profession': ' Doctor') ('Name': 'Miller', ' Age': ' 22', ' Profession': ' Engineer') 

As we can see, the entries of the first row are the dictionary keys. And, the entries in the other rows are the dictionary values.

Here, csv_file is a csv.DictReader() object. The object can be iterated over using a for loop. The csv.DictReader() returned an OrderedDict type for each row. That's why we used dict() to convert each row to a dictionary.

Notice that, we have explicitly used the dict() method to create dictionaries inside the for loop.

 print(dict(row)) 

Note: Starting from Python 3.8, csv.DictReader() returns a dictionary for each row, and we do not need to use dict() explicitly.

The full syntax of the csv.DictReader() class is:

 csv.DictReader(file, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds) 

To learn more about it in detail, visit: Python csv.DictReader() class

Python csv.DictWriter() Class

The objects of csv.DictWriter() class can be used to write to a CSV file from a Python dictionary.

The minimal syntax of the csv.DictWriter() class is:

 csv.DictWriter(file, fieldnames) 

Here,

  • file - CSV file where we want to write to
  • fieldnames - a list object which should contain the column headers specifying the order in which data should be written in the CSV file

Example 7: Python csv.DictWriter()

 import csv with open('players.csv', 'w', newline='') as file: fieldnames = ('player_name', 'fide_rating') writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow(('player_name': 'Magnus Carlsen', 'fide_rating': 2870)) writer.writerow(('player_name': 'Fabiano Caruana', 'fide_rating': 2822)) writer.writerow(('player_name': 'Ding Liren', 'fide_rating': 2801)) 

The program creates a players.csv file with the following entries:

 player_name,fide_rating Magnus Carlsen,2870 Fabiano Caruana,2822 Ding Liren,2801 

The full syntax of the csv.DictWriter() class is:

 csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds) 

To learn more about it in detail, visit: Python csv.DictWriter() class

Using the Pandas library to Handle CSV files

Pandas is a popular data science library in Python for data manipulation and analysis. If we are working with huge chunks of data, it's better to use pandas to handle CSV files for ease and efficiency.

Before we can use pandas, we need to install it. To learn more, visit: How to install Pandas?

Once we install it, we can import Pandas as:

 import pandas as pd 

To read the CSV file using pandas, we can use the read_csv() function.

 import pandas as pd pd.read_csv("people.csv") 

Ở đây, chương trình đọc people.csv từ thư mục hiện tại.

Để ghi vào tệp CSV, chúng ta cần gọi to_csv()hàm của DataFrame.

 import pandas as pd # creating a data frame df = pd.DataFrame((('Jack', 24), ('Rose', 22)), columns = ('Name', 'Age')) # writing data frame to a CSV file df.to_csv('person.csv') 

Ở đây, chúng tôi đã tạo một DataFrame bằng pd.DataFrame()phương pháp này. Sau đó, to_csv()hàm cho đối tượng này được gọi, để viết thành person.csv .

Để tìm hiểu thêm, hãy truy cập:

  • Python pandas.read_csv (trang web chính thức)
  • Python pandas.pandas.DataFrame.to_csv (trang web chính thức)

thú vị bài viết...