Trong hướng dẫn này, chúng ta sẽ học cách đọc các tệp CSV với các định dạng khác nhau bằng Python với sự trợ giúp của các ví dụ.
Chúng tôi sẽ sử dụng độc quyền csv
mô-đun được tích hợp trong Python cho nhiệm vụ này. Nhưng trước tiên, chúng ta sẽ phải nhập mô-đun dưới dạng:
import csv
Chúng tôi đã trình bày những kiến thức cơ bản về cách sử dụng csv
mô-đun để đọc và ghi vào tệp CSV. Nếu bạn không có bất kỳ ý tưởng nào về việc sử dụng csv
mô-đun, hãy xem hướng dẫn của chúng tôi về Python CSV: Đọc và Ghi tệp CSV
Cách sử dụng cơ bản của csv.reader ()
Hãy xem một ví dụ cơ bản về việc sử dụng csv.reader()
để làm mới kiến thức hiện có của bạn.
Ví dụ 1: Đọc tệp CSV bằng csv.reader ()
Giả sử chúng ta có một tệp CSV với các mục sau:
SN, Tên, Đóng góp 1, Linus Torvalds, Nhân Linux 2, Tim Berners-Lee, World Wide Web 3, Guido van Rossum, Lập trình Python
Chúng ta có thể đọc nội dung của tệp bằng chương trình sau:
import csv with open('innovators.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
Đầu ra
('SN', 'Tên', 'Đóng góp') ('1', 'Linus Torvalds', 'Nhân Linux') ('2', 'Tim Berners-Lee', 'World Wide Web') ('3' , 'Guido van Rossum', 'Lập trình Python')
Ở đây, chúng tôi đã mở tệp innovator.csv ở chế độ đọc bằng open()
chức năng.
Để 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 reader
tượng sau đó được lặp lại bằng cách sử dụng một for
vòng lặp để in nội dung của mỗi hàng.
Bây giờ, chúng ta sẽ xem xét các tệp CSV với các định dạng khác nhau. Sau đó chúng ta sẽ học cách tùy chỉnh csv.reader()
chức năng để đọc chúng.
Tệp CSV có Dấu phân cách tùy chỉnh
Theo mặc định, dấu phẩy được sử dụng làm dấu phân cách trong tệp CSV. Tuy nhiên, một số tệp CSV có thể sử dụng dấu phân cách khác với dấu phẩy. Một số ít phổ biến là |
và
.
Giả sử tệp innovator.csv trong Ví dụ 1 đang sử dụng tab làm dấu phân cách. Để đọc tệp, chúng ta có thể truyền một delimiter
tham số bổ sung 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('innovators.csv', 'r') as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row)
Đầu ra
('SN', 'Tên', 'Đóng góp') ('1', 'Linus Torvalds', 'Nhân Linux') ('2', 'Tim Berners-Lee', 'World Wide Web') ('3' , 'Guido van Rossum', 'Lập trình Python')
Như chúng ta có thể thấy, tham số tùy chọn delimiter = ' '
giúp chỉ định reader
đối tượng mà tệp CSV chúng ta đang đọc, có các tab là dấu phân cách.
Tệp CSV có khoảng trắng ban đầu
Một số tệp CSV có thể có ký tự khoảng trắng sau dấu phân cách. Khi chúng tôi sử dụng csv.reader()
chức năng mặc định để đọc các tệp CSV này, chúng tôi cũng sẽ nhận được khoảng trắng trong đầu ra.
Để loại bỏ các khoảng trắng ban đầu này, chúng ta cần truyền một tham số bổ sung được gọi là skipinitialspace
. Chúng ta hãy xem xét một ví dụ:
Ví dụ 3: Đọc tệp CSV có khoảng trắng ban đầu
Giả sử chúng ta có một tệp CSV có tên là people.csv với nội dung sau:
SN, Tên, Thành phố 1, John, Washington 2, Eric, Los Angeles 3, Brad, Texas
Chúng ta có thể đọc tệp CSV như sau:
import csv with open('people.csv', 'r') as csvfile: reader = csv.reader(csvfile, skipinitialspace=True) for row in reader: print(row)
Đầu ra
('SN', 'Tên', 'Thành phố') ('1', 'John', 'Washington') ('2', 'Eric', 'Los Angeles') ('3', 'Brad', ' Texas ')
Chương trình tương tự như các ví dụ khác nhưng có một skipinitialspace
tham số bổ sung được đặt thành True.
Điều này cho phép reader
đối tượng biết rằng các mục nhập có khoảng trắng ban đầu. Do đó, các khoảng trắng ban đầu hiện diện sau dấu phân cách sẽ bị loại bỏ.
Tệp CSV có dấu ngoặc kép
Một số tệp CSV có thể có dấu ngoặc kép xung quanh mỗi hoặc một số mục nhập.
Hãy lấy dấu ngoặc kép.csv làm ví dụ, với các mục sau:
"SN", "Tên", "Trích dẫn" 1, Đức Phật, "Điều chúng ta nghĩ rằng mình trở thành" 2, Mark Twain, "Không bao giờ hối tiếc về bất cứ điều gì khiến bạn mỉm cười" 3, Oscar Wilde, "Hãy là chính mình, mọi người khác đều đã mất rồi"
Sử dụng csv.reader()
ở chế độ tối thiểu sẽ dẫn đến kết quả đầu ra có dấu ngoặc kép.
Để loại bỏ chúng, chúng ta sẽ phải sử dụng một tham số tùy chọn khác được gọi là quoting
.
Hãy xem một ví dụ về cách đọc chương trình trên.
Ví dụ 4: Đọc tệp CSV có dấu ngoặc kép
import csv with open('person1.csv', 'r') as file: reader = csv.reader(file, quoting=csv.QUOTE_ALL, skipinitialspace=True) for row in reader: print(row)
Đầu ra
('SN', 'Name', 'Quotes') ('1', 'Buddha', 'What we think we become') ('2', 'Mark Twain', 'Never regret anything that made you smile') ('3', 'Oscar Wilde', 'Be yourself everyone else is already taken')
As you can see, we have passed csv.QUOTE_ALL
to the quoting
parameter. It is a constant defined by the csv
module.
csv.QUOTE_ALL
specifies the reader object that all the values in the CSV file are present inside quotation marks.
There are 3 other predefined constants you can pass to the quoting
parameter:
csv.QUOTE_MINIMAL
- Specifiesreader
object that CSV file has quotes around those entries which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.csv.QUOTE_NONNUMERIC
- Specifies thereader
object that the CSV file has quotes around the non-numeric entries.csv.QUOTE_NONE
- Specifies the reader object that none of the entries have quotes around them.
Dialects in CSV module
Notice in Example 4 that we have passed multiple parameters (quoting
and skipinitialspace
) to the csv.reader()
function.
This practice is acceptable when dealing with one or two files. But it will make the code more redundant and ugly once we start working with multiple CSV files with similar formats.
As a solution to this, the csv
module offers dialect
as an optional parameter.
Dialect helps in grouping together many specific formatting patterns like delimiter
, skipinitialspace
, quoting
, escapechar
into a single dialect name.
It can then be passed as a parameter to multiple writer
or reader
instances.
Example 5: Read CSV files using dialect
Suppose we have a CSV file (office.csv) with the following content:
"ID"| "Name"| "Email" "A878"| "Alfonso K. Hamby"| "[email protected]" "F854"| "Susanne Briard"| "[email protected]" "E833"| "Katja Mauer"| "[email protected]"
The CSV file has initial spaces, quotes around each entry, and uses a |
delimiter.
Instead of passing three individual formatting patterns, let's look at how to use dialects to read this file.
import csv csv.register_dialect('myDialect', delimiter='|', skipinitialspace=True, quoting=csv.QUOTE_ALL) with open('office.csv', 'r') as csvfile: reader = csv.reader(csvfile, dialect='myDialect') for row in reader: print(row)
Output
('ID', 'Name', 'Email') ("A878", 'Alfonso K. Hamby', '[email protected]') ("F854", 'Susanne Briard', '[email protected]') ("E833", 'Katja Mauer', '[email protected]')
From this example, we can see that the csv.register_dialect()
function is used to define a custom dialect. It has the following syntax:
csv.register_dialect(name(, dialect(, **fmtparams)))
The custom dialect requires a name in the form of a string. Other specifications can be done either by passing a sub-class of Dialect
class, or by individual formatting patterns as shown in the example.
While creating the reader object, we pass dialect='myDialect'
to specify that the reader instance must use that particular dialect.
The advantage of using dialect
is that it makes the program more modular. Notice that we can reuse 'myDialect' to open other files without having to re-specify the CSV format.
Read CSV files with csv.DictReader()
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 a CSV file (people.csv) with the following entries:
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
Using csv.Sniffer class
The Sniffer
class is used to deduce the format of a CSV file.
The Sniffer
class offers two methods:
sniff(sample, delimiters=None)
- This function analyses a given sample of the CSV text and returns aDialect
subclass that contains all the parameters deduced.
An optional delimiters parameter can be passed as a string containing possible valid delimiter characters.
has_header(sample)
- This function returnsTrue
orFalse
based on analyzing whether the sample CSV has the first row as column headers.
Let's look at an example of using these functions:
Example 7: Using csv.Sniffer() to deduce the dialect of CSV files
Suppose we have a CSV file (office.csv) with the following content:
"ID"| "Name"| "Email" A878| "Alfonso K. Hamby"| "[email protected]" F854| "Susanne Briard"| "[email protected]" E833| "Katja Mauer"| "[email protected]"
Let's look at how we can deduce the format of this file using csv.Sniffer()
class:
import csv with open('office.csv', 'r') as csvfile: sample = csvfile.read(64) has_header = csv.Sniffer().has_header(sample) print(has_header) deduced_dialect = csv.Sniffer().sniff(sample) with open('office.csv', 'r') as csvfile: reader = csv.reader(csvfile, deduced_dialect) for row in reader: print(row)
Output
True ('ID', 'Name', 'Email') ('A878', 'Alfonso K. Hamby', '[email protected]') ('F854', 'Susanne Briard', '[email protected]') ('E833', 'Katja Mauer', '[email protected]')
As you can see, we read only 64 characters of office.csv and stored it in the sample variable.
This sample was then passed as a parameter to the Sniffer().has_header()
function. It deduced that the first row must have column headers. Thus, it returned True
which was then printed out.
Tương tự, mẫu cũng được chuyển đến Sniffer().sniff()
hàm. Nó trả về tất cả các tham số được suy ra dưới dạng một Dialect
lớp con, sau đó được lưu trữ trong biếnised_dialect.
Sau đó, chúng tôi đã mở lại tệp CSV và chuyển deduced_dialect
biến làm tham số cho csv.reader()
.
Đó là một cách chính xác có thể dự đoán delimiter
, quoting
và skipinitialspace
tham số trong office.csv file mà không cần chúng ta nhắc đến họ một cách rõ ràng.
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.
Đọc đề xuất: Ghi vào tệp CSV bằng Python