CSV fájlok írása Pythonban

Ebben az oktatóanyagban megtanulunk példák segítségével különböző Python formátumú CSV fájlokat írni.

Kizárólag csva Pythonba épített modult fogjuk használni erre a feladatra. De először a modult kell importálnunk:

 import csv 

Már áttekintettük a csvmodul CSV fájlokba történő olvasására és írására vonatkozó alapjait . Ha nincs ötlete a csvmodul használatával kapcsolatban, olvassa el a Python CSV-re vonatkozó oktatóanyagunkat: CSV-fájlok olvasása és írása

A csv.writer () alapvető használata

Nézzünk meg egy alapvető példát csv.writer()a meglévő ismeretek frissítésére.

1. példa: Írjon CSV fájlokba a csv.writer () segítségével

Tegyük fel, hogy CSV fájlt akarunk írni a következő bejegyzésekkel:

 SN, név, 1. hozzájárulás, Linus Torvalds, Linux Kernel 2, Tim Berners-Lee, világháló 3, Guido van Rossum, Python programozás 

Így csináljuk.

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

A fenti program futtatásakor egy innovators.csv fájl jön létre az aktuális munkakönyvtárban a megadott bejegyzésekkel.

Itt megnyitottuk az innovators.csv fájlt írási módban a open()funkció használatával .

Ha többet szeretne megtudni a fájlok Python-ban történő megnyitásáról, keresse fel a következő címet: Python File Input / Output

Ezután a csv.writer()függvény egy writerobjektum létrehozására szolgál . Ezután a writer.writerow()függvény segítségével egyetlen sort írnak a CSV fájlba.

2. példa: Több sor írása írójelekkel ()

Ha a kétdimenziós lista tartalmát CSV fájlba kell írnunk, a következőképpen tehetjük meg.

 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) 

A program kimenete megegyezik az 1. példában leírtakkal .

Itt adjuk át a kétdimenziós listánkat a writer.writerows()függvénynek, amely a lista tartalmát a CSV fájlba írja.

Most nézzük meg, hogyan írhatunk CSV fájlokat különböző formátumokban. Ezután megtanuljuk, hogyan kell testre szabni a csv.writer()függvényt azok megírásához.

CSV-fájlok egyéni elválasztókkal

Alapértelmezés szerint vesszőt használnak elválasztóként egy CSV-fájlban. Egyes CSV-fájlok azonban vesszőtől eltérő elválasztókat is használhatnak. Kevés népszerű |és .

Tegyük fel, hogy |elválasztóként szeretnénk használni az 1. példa innovators.csv fájljában . A fájl megírásához további paramétereket adhatunk át a függvénynek.delimitercsv.writer()

Vegyünk egy példát.

3. példa: CSV-fájl írása csőelválasztóval

 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) 

Kimenet

 SN | Név | Hozzájárulás 1 | Linus Torvalds | Linux Kernel 2 | Tim Berners-Lee | Világháló 3 | Guido van Rossum | Python programozás 

Mint láthatjuk, az opcionális paraméter delimiter = '|'segít meghatározni azt az writerobjektumot, amelyet a CSV fájlnak |elválasztóként kell tartalmaznia .

CSV fájlok Idézetekkel

Néhány CSV-fájlban idézőjelek találhatók mindegyik vagy néhány bejegyzés körül.

Vegyük példaként az quotes.csv fájlt a következő bejegyzésekkel:

 "SN"; "Név"; "Idézetek" 1; "Buddha"; "Amiről azt gondoljuk, hogy" 2; "Mark Twain" leszünk; "Soha ne bánj semmit, ami mosolygásra késztetett" 3; "Oscar Wilde"; "Légy önmagad mindenki más már foglalt" 

Az csv.writer()alapértelmezett használat nem fogja hozzáadni ezeket az idézeteket a bejegyzésekhez.

Hozzáadásukhoz egy másik opcionális paramétert kell használnunk quoting.

Vegyünk egy példát arra, hogy az idézet hogyan használható a nem numerikus értékek körül és ;elválasztóként.

4. példa: CSV fájlokat írjon idézőjelekkel

 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) 

Kimenet

 "SN"; "Név"; "Idézetek" 1; "Buddha"; "Amiről azt gondoljuk, hogy" 2; "Mark Twain" leszünk; "Soha ne bánj semmit, ami mosolygásra késztetett" 3; "Oscar Wilde"; "Légy önmagad mindenki más már foglalt" 

Itt a quotes.csv fájl jön létre a munkakönyvtárban a fenti bejegyzésekkel.

Amint láthatja, átadtuk csv.QUOTE_NONNUMERICa quotingparamétert. Ez egy állandó, amelyet a csvmodul határoz meg .

csv.QUOTE_NONNUMERICmegadja azt az writerobjektumot, amelyet idézőjelekkel kell hozzáadni a nem numerikus bejegyzések köré.

Három másik előre definiált konstans adható át a quotingparaméternek:

  • csv.QUOTE_ALL- Megadja az writerobjektumot, amely CSV-fájlt idézőjelekkel ír az összes bejegyzés köré.
  • csv.QUOTE_MINIMAL- Megadja az writerobjektumot, hogy csak azokat a mezőket idézze, amelyek speciális karaktereket tartalmaznak ( elválasztó , idézőjel vagy bármely karakter a vonalmeghatározóban )
  • csv.QUOTE_NONE- Megadja azt az writerobjektumot, amelyet egyik bejegyzés sem idézhet. Ez az alapértelmezett érték.

CSV fájlok egyedi idézőjeles karakterrel

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.

Ajánlott olvasmány: Olvassa el a CSV fájlokat Pythonban

érdekes cikkek...