Schreiben von CSV-Dateien in Python

In diesem Tutorial lernen wir anhand von Beispielen, CSV-Dateien mit verschiedenen Formaten in Python zu schreiben.

csvFür diese Aufgabe verwenden wir ausschließlich das in Python integrierte Modul. Aber zuerst müssen wir das Modul importieren als:

 import csv 

Wir haben bereits die Grundlagen der Verwendung des csvModuls zum Lesen und Schreiben in CSV-Dateien behandelt. Wenn Sie keine Ahnung haben, wie Sie das csvModul verwenden sollen, lesen Sie unser Tutorial zu Python CSV: Lesen und Schreiben von CSV-Dateien

Grundlegende Verwendung von csv.writer ()

Schauen wir uns ein grundlegendes Beispiel für die csv.writer()Aktualisierung Ihres vorhandenen Wissens an.

Beispiel 1: Schreiben Sie mit csv.writer () in CSV-Dateien

Angenommen, wir möchten eine CSV-Datei mit den folgenden Einträgen schreiben:

 SN, Name, Beitrag 1, Linus Torvalds, Linux-Kernel 2, Tim Berners-Lee, World Wide Web 3, Guido van Rossum, Python-Programmierung 

So machen wir es.

 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")) 

Wenn wir das obige Programm ausführen, wird im aktuellen Arbeitsverzeichnis eine Datei innovators.csv mit den angegebenen Einträgen erstellt.

Hier haben wir die Datei innovators.csv im Schreibmodus mit der open()Funktion geöffnet .

Weitere Informationen zum Öffnen von Dateien in Python finden Sie unter: Eingabe / Ausgabe von Python-Dateien

Als nächstes wird die csv.writer()Funktion verwendet, um ein writerObjekt zu erstellen . Die writer.writerow()Funktion wird dann verwendet, um einzelne Zeilen in die CSV-Datei zu schreiben.

Beispiel 2: Schreiben mehrerer Zeilen mit Writerows ()

Wenn wir den Inhalt der zweidimensionalen Liste in eine CSV-Datei schreiben müssen, gehen wir wie folgt vor.

 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) 

Die Ausgabe des Programms ist dieselbe wie in Beispiel 1 .

Hier wird unsere zweidimensionale Liste an die writer.writerows()Funktion übergeben, um den Inhalt der Liste in die CSV-Datei zu schreiben.

Nun wollen wir sehen, wie wir CSV-Dateien in verschiedenen Formaten schreiben können. Wir werden dann lernen, wie man die csv.writer()Funktion zum Schreiben anpasst.

CSV-Dateien mit benutzerdefinierten Trennzeichen

Standardmäßig wird ein Komma als Trennzeichen in einer CSV-Datei verwendet. Einige CSV-Dateien können jedoch andere Trennzeichen als Komma verwenden. Nur wenige beliebte sind |und .

Angenommen, wir möchten |als Trennzeichen in der Datei innovators.csv von Beispiel 1 verwenden . Um diese Datei zu schreiben, können wir delimiterder csv.writer()Funktion einen zusätzlichen Parameter übergeben .

Nehmen wir ein Beispiel.

Beispiel 3: Schreiben einer CSV-Datei mit Rohrbegrenzer

 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) 

Ausgabe

 SN | Name | Beitrag 1 | Linus Torvalds | Linux-Kernel 2 | Tim Berners-Lee | World Wide Web 3 | Guido van Rossum | Python-Programmierung 

Wie wir sehen können, delimiter = '|'hilft der optionale Parameter dabei , das writerObjekt anzugeben, das die CSV-Datei |als Trennzeichen haben soll.

CSV-Dateien mit Anführungszeichen

Einige CSV-Dateien enthalten Anführungszeichen um jeden oder einige der Einträge.

Nehmen wir als Beispiel quote.csv mit den folgenden Einträgen:

 "SN"; "Name"; "Zitate" 1; "Buddha"; "Was wir denken, wir werden" 2; "Mark Twain"; "Bereue niemals etwas, das dich zum Lächeln gebracht hat" 3; "Oscar Wilde"; "Sei du selbst jeder andere ist schon vergeben" 

Bei Verwendung csv.writer()von standardmäßig werden diese Anführungszeichen nicht zu den Einträgen hinzugefügt.

Um sie hinzuzufügen, müssen wir einen anderen optionalen Parameter namens verwenden quoting.

Nehmen wir ein Beispiel dafür, wie Anführungszeichen für nicht numerische Werte und ;als Trennzeichen verwendet werden können.

Beispiel 4: Schreiben Sie CSV-Dateien mit Anführungszeichen

 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) 

Ausgabe

 "SN"; "Name"; "Zitate" 1; "Buddha"; "Was wir denken, wir werden" 2; "Mark Twain"; "Bereue niemals etwas, das dich zum Lächeln gebracht hat" 3; "Oscar Wilde"; "Sei du selbst jeder andere ist schon vergeben" 

Hier wird die Datei quote.csv im Arbeitsverzeichnis mit den obigen Einträgen erstellt.

Wie Sie sehen, haben wir csv.QUOTE_NONNUMERICden quotingParameter übergeben. Es ist eine vom csvModul definierte Konstante .

csv.QUOTE_NONNUMERICGibt das writerObjekt an, das Anführungszeichen um die nicht numerischen Einträge hinzugefügt werden sollen.

Es gibt 3 weitere vordefinierte Konstanten, die Sie an den quotingParameter übergeben können:

  • csv.QUOTE_ALL- Gibt das writerObjekt an, in das eine CSV-Datei mit Anführungszeichen um alle Einträge geschrieben werden soll.
  • csv.QUOTE_MINIMAL- Gibt das writerObjekt an, das nur die Felder in Anführungszeichen setzt, die Sonderzeichen enthalten ( Trennzeichen , Anführungszeichen oder beliebige Zeichen im Lineterminator ).
  • csv.QUOTE_NONE- Gibt das writerObjekt an, für das keiner der Einträge in Anführungszeichen gesetzt werden soll. Dies ist der Standardwert.

CSV-Dateien mit benutzerdefiniertem Anführungszeichen

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 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)) 

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.

Empfohlene Lektüre: Lesen Sie CSV-Dateien in Python

Interessante Beiträge...