I denne vejledning lærer vi at skrive CSV-filer med forskellige formater i Python ved hjælp af eksempler.
Vi vil udelukkende bruge det csv
modul, der er indbygget i Python, til denne opgave. Men først skal vi importere modulet som:
import csv
Vi har allerede dækket det grundlæggende om, hvordan man bruger csv
modulet til at læse og skrive i CSV-filer. Hvis du ikke har nogen idé om at bruge csv
modulet, skal du tjekke vores tutorial om Python CSV: Læs og skriv CSV-filer
Grundlæggende brug af csv.writer ()
Lad os se på et grundlæggende eksempel på at bruge csv.
writer
()
til at opdatere din eksisterende viden.
Eksempel 1: Skriv til CSV-filer med csv.writer ()
Antag, at vi vil skrive en CSV-fil med følgende poster:
SN, Navn, Bidrag 1, Linus Torvalds, Linux Kernel 2, Tim Berners-Lee, World Wide Web 3, Guido van Rossum, Python Programming
Sådan gør vi det.
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"))
Når vi kører ovenstående program, oprettes en innovators.csv- fil i den aktuelle arbejdsmappe med de givne poster.
Her har vi åbnet filen innovators.csv i skrivemåde ved hjælp af open()
funktionen.
For at lære mere om åbning af filer i Python, besøg: Python File Input / Output
Dernæst csv.writer()
bruges funktionen til at oprette et writer
objekt. Den writer.writerow()
funktion bruges derefter til at skrive enkelte rækker i CSV-filen.
Eksempel 2: Skrivning af flere rækker medwrows ()
Hvis vi har brug for at skrive indholdet af den 2-dimensionelle liste til en CSV-fil, kan vi her gøre det.
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)
Programmets output er den samme som i eksempel 1 .
Her videregives vores 2-dimensionelle liste til writer.writerows()
funktionen for at skrive indholdet af listen til CSV-filen.
Lad os nu se, hvordan vi kan skrive CSV-filer i forskellige formater. Vi lærer derefter, hvordan vi tilpasser csv.writer()
funktionen til at skrive dem.
CSV-filer med brugerdefinerede afgrænsere
Som standard bruges et komma som en afgrænser i en CSV-fil. Nogle CSV-filer kan dog bruge andre afgrænsere end komma. Få populære er |
og
.
Antag, at vi vil bruge |
som en afgrænser i innovators.csv- filen i eksempel 1 . For at skrive denne fil kan vi videregive en ekstra delimiter
parameter til csv.writer()
funktionen.
Lad os tage et eksempel.
Eksempel 3: Skriv CSV-fil med rørafgrænser
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)
Produktion
SN | Navn | Bidrag 1 | Linus Torvalds | Linux Kernel 2 | Tim Berners-Lee | World Wide Web 3 | Guido van Rossum | Python-programmering
Som vi kan se, delimiter = '|'
hjælper den valgfri parameter med at specificere det writer
objekt, som CSV-filen skal have |
som en afgrænser.
CSV-filer med tilbud
Nogle CSV-filer har citater omkring hver eller nogle af posterne.
Lad os tage quotes.csv som et eksempel med følgende poster:
"SN"; "Navn"; "Citater" 1; "Buddha"; "Hvad vi synes vi bliver" 2; "Mark Twain"; "Beklager aldrig noget der fik dig til at smile" 3; "Oscar Wilde"; "Vær dig selv alle andre er allerede taget "
Brug csv.writer()
som standard vil ikke føje disse tilbud til posterne.
For at tilføje dem skal vi bruge en anden valgfri parameter kaldet quoting
.
Lad os tage et eksempel på, hvordan citering kan bruges omkring de ikke-numeriske værdier og ;
som afgrænsere.
Eksempel 4: Skriv CSV-filer med anførselstegn
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)
Produktion
"SN"; "Navn"; "Citater" 1; "Buddha"; "Hvad vi synes vi bliver" 2; "Mark Twain"; "Beklager aldrig noget der fik dig til at smile" 3; "Oscar Wilde"; "Vær dig selv alle andre er allerede taget "
Her oprettes filen quotes.csv i arbejdskataloget med ovenstående poster.
Som du kan se, er vi gået csv.QUOTE_NONNUMERIC
til quoting
parameteren. Det er en konstant defineret af csv
modulet.
csv.QUOTE_NONNUMERIC
angiver writer
objektet, som citater skal tilføjes omkring de ikke-numeriske poster.
Der er 3 andre foruddefinerede konstanter, du kan overføre til quoting
parameteren:
csv.QUOTE_ALL
- Specificerer detwriter
objekt, der skal skrives CSV-fil med anførselstegn omkring alle poster.csv.QUOTE_MINIMAL
- Angiverwriter
objektet, der kun skal citere de felter, der indeholder specialtegn ( afgrænser , citattegn eller andre tegn i linjeterminator )csv.QUOTE_NONE
- Angiverwriter
objektet, som ingen af posterne skal citeres. Det er standardværdien.
CSV-filer med brugerdefineret citattegn
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.
Anbefalet læsning: Læs CSV-filer i Python