Trong hướng dẫn này, chúng ta sẽ học cách viết 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.writer ()
Hãy xem một ví dụ cơ bản về việc sử dụng csv.
writer
()
để làm mới kiến thức hiện có của bạn.
Ví dụ 1: Ghi vào tệp CSV bằng csv.writer ()
Giả sử chúng ta muốn viết 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
Đây là cách chúng tôi làm điều đó.
import csv with open('innovators.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(("SN", "Name", "Contribution")) writer.writerow((1, "Linus Torvalds", "Linux Kernel")) writer.writerow((2, "Tim Berners-Lee", "World Wide Web")) writer.writerow((3, "Guido van Rossum", "Python Programming"))
Khi chúng tôi chạy chương trình trên, một tệp innovator.csv được tạo trong thư mục làm việc hiện tại với các mục đã cho.
Ở đây, chúng tôi đã mở tệp innovator.csv ở chế độ ghi bằng open()
hàm.
Để 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
Tiếp theo, csv.writer()
hàm được sử dụng để tạo một writer
đối tượng. Sau đó, writer.writerow()
hàm được sử dụng để ghi các hàng đơn vào tệp CSV.
Ví dụ 2: Viết nhiều hàng với ghi ()
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 row_list = (("SN", "Name", "Contribution"), (1, "Linus Torvalds", "Linux Kernel"), (2, "Tim Berners-Lee", "World Wide Web"), (3, "Guido van Rossum", "Python Programming")) with open('protagonist.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(row_list)
Đầu ra của chương trình giống như trong Ví dụ 1 .
Tại đây, danh sách 2 chiều của chúng ta được chuyển cho writer.writerows()
hàm ghi nội dung của danh sách vào tệp CSV.
Bây giờ, hãy xem cách chúng ta có thể viết tệp CSV ở các định dạng khác nhau. Sau đó chúng ta sẽ học cách tùy chỉnh csv.writer()
hàm để viết 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ử chúng ta muốn sử dụng |
làm dấu phân tách trong tệp innovator.csv của Ví dụ 1 . Để ghi tệp này, chúng ta có thể truyền một delimiter
tham số bổ sung cho csv.writer()
hàm.
Hãy lấy một ví dụ.
Ví dụ 3: Viết tệp CSV có dấu phân cách ống
import csv data_list = (("SN", "Name", "Contribution"), (1, "Linus Torvalds", "Linux Kernel"), (2, "Tim Berners-Lee", "World Wide Web"), (3, "Guido van Rossum", "Python Programming")) with open('innovators.csv', 'w', newline='') as file: writer = csv.writer(file, delimiter='|') writer.writerows(data_list)
Đầ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 writer
đối tượng mà tệp CSV nên có |
làm dấu phân cách.
Tệp CSV có Trích dẫn
Một số tệp CSV 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 tôi nghĩ rằng chúng tôi 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 bạn Mọi người khác đã được thực hiện"
Sử dụng csv.writer()
theo mặc định sẽ không thêm các dấu ngoặc kép này vào các mục nhập.
Để thêm 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 lấy một ví dụ về cách trích dẫn có thể được sử dụng xung quanh các giá trị không phải số và ;
làm dấu phân cách.
Ví dụ 4: Viết tệp CSV có dấu ngoặc kép
import csv row_list = ( ("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") ) with open('quotes.csv', 'w', newline='') as file: writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';') writer.writerows(row_list)
Đầu ra
"SN"; "Tên"; "Trích dẫn" 1; "Đức Phật"; "Điều chúng tôi nghĩ rằng chúng tôi 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 bạn Mọi người khác đã được thực hiện"
Ở đây, tệp quote.csv được tạo trong thư mục làm việc với các mục trên.
Như bạn có thể thấy, chúng tôi đã chuyển csv.QUOTE_NONNUMERIC
đến quoting
tham số. Nó là một hằng số được xác định bởi csv
mô-đun.
csv.QUOTE_NONNUMERIC
chỉ định writer
đối tượng mà dấu ngoặc kép sẽ được thêm vào xung quanh các mục nhập không phải là số.
Có 3 hằng số được xác định trước khác mà bạn có thể chuyển cho quoting
tham số:
csv.QUOTE_ALL
- Chỉ địnhwriter
đối tượng ghi tệp CSV với dấu ngoặc kép xung quanh tất cả các mục.csv.QUOTE_MINIMAL
- Chỉ địnhwriter
đối tượng chỉ trích dẫn những trường có chứa các ký tự đặc biệt ( dấu phân cách , dấu ngoặc kép hoặc bất kỳ ký tự nào trong bộ định tuyến )csv.QUOTE_NONE
- Chỉ địnhwriter
đối tượng mà không mục nào được trích dẫn. Nó là giá trị mặc định.
Tệp CSV với ký tự trích dẫn tùy chỉnh
We can also write CSV files with custom quoting characters. For that, we will have to use an optional parameter called quotechar
.
Let's take an example of writing quotes.csv file in Example 4, but with *
as the quoting character.
Example 5: Writing CSV files with custom quoting character
import csv row_list = ( ("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") ) with open('quotes.csv', 'w', newline='') as file: writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';', quotechar='*') writer.writerows(row_list)
Output
*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*
Here, we can see that quotechar='*'
parameter instructs the writer
object to use *
as quote for all non-numeric values.
Dialects in CSV module
Notice in Example 5 that we have passed multiple parameters (quoting
, delimiter
and quotechar
) to the csv.writer()
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 6: Write CSV file using dialect
Suppose we want to write 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 quotes around each entry and uses |
as a delimiter.
Instead of passing two individual formatting patterns, let's look at how to use dialects to write this file.
import csv row_list = ( ("ID", "Name", "Email"), ("A878", "Alfonso K. Hamby", "[email protected]"), ("F854", "Susanne Briard", "[email protected]"), ("E833", "Katja Mauer", "[email protected]") ) csv.register_dialect('myDialect', delimiter='|', quoting=csv.QUOTE_ALL) with open('office.csv', 'w', newline='') as file: writer = csv.writer(file, dialect='myDialect') writer.writerows(row_list)
Output
"ID"|"Name"|"Email" "A878"|"Alfonso K. Hamby"|"[email protected]" "F854"|"Susanne Briard"|"[email protected]" "E833"|"Katja Mauer"|"[email protected]"
Here, office.csv is created in the working directory with the above contents.
From this example, we can see that the csv.register_dialect()
function is used to define a custom dialect. Its syntax is:
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 the Dialect
class, or by individual formatting patterns as shown in the example.
While creating the writer
object, we pass dialect='myDialect'
to specify that the writer 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 write other CSV files without having to re-specify the CSV format.
Write CSV files with csv.DictWriter()
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 tofieldnames
- alist
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))
Output
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
CSV files with lineterminator
A lineterminator
is a string used to terminate lines produced by writer
objects. The default value is . You can change its value by passing any string as a
lineterminator
parameter.
However, the reader
object only recognizes or
as
lineterminator
values. So using other characters as line terminators is highly discouraged.
doublequote & escapechar in CSV module
In order to separate delimiter characters in the entries, the csv
module by default quotes the entries using quotation marks.
So, if you had an entry: He is a strong, healthy man, it will be written as: "He is a strong, healthy man".
Similarly, the csv
module uses double quotes in order to escape the quote character present in the entries by default.
If you had an entry: Go to "programiz.com", it would be written as: "Go to ""programiz.com""".
Here, we can see that each "
is followed by a "
to escape the previous one.
doublequote
It handles how quotechar
present in the entry themselves are quoted. When True
, the quoting character is doubled and when False
, the escapechar
is used as a prefix to the quotechar
. By default its value is True
.
escapechar
escapechar
parameter is a string to escape the delimiter if quoting is set to csv.QUOTE_NONE
and quotechar if doublequote is False
. Its default value is None.
Example 8: Using escapechar in csv writer
import csv row_list = ( ('Book', 'Quote'), ('Lord of the Rings', '"All we have to decide is what to do with the time that is given us."'), ('Harry Potter', '"It matters not what someone is born, but what they grow to be."') ) with open('book.csv', 'w', newline='') as file: writer = csv.writer(file, escapechar='/', quoting=csv.QUOTE_NONE) writer.writerows(row_list)
Output
Book,Quote Lord of the Rings,/"All we have to decide is what to do with the time that is given us./" Harry Potter,/"It matters not what someone is born/, but what they grow to be./"
Here, we can see that /
is prefix to all the "
and ,
because we specified quoting=csv.QUOTE_NONE
.
If it wasn't defined, then, the output would be:
Book,Quote Lord of the Rings,"""All we have to decide is what to do with the time that is given us.""" Harry Potter,"""It matters not what someone is born, but what they grow to be."""
Since we allow quoting, the entries with special characters("
in this case) are double-quoted. The entries with delimiter
are also enclosed within quote characters.(Starting and closing quote characters)
The remaining quote characters are to escape the actual "
present as part of the string, so that they are not interpreted as quotechar.
Note: The csv module can also be used for other file extensions (like: .txt) as long as their contents are in proper structure.
Đọc đề xuất: Đọc tệp CSV bằng Python