Σε αυτό το σεμινάριο, θα μάθουμε να γράφουμε αρχεία CSV με διαφορετικές μορφές στο Python με τη βοήθεια παραδειγμάτων.
Θα χρησιμοποιήσουμε αποκλειστικά τη csv
μονάδα που είναι ενσωματωμένη στην Python για αυτήν την εργασία. Αλλά πρώτα, θα πρέπει να εισαγάγουμε τη λειτουργική μονάδα ως:
import csv
Έχουμε ήδη καλύψει τα βασικά του τρόπου χρήσης της csv
ενότητας για ανάγνωση και εγγραφή σε αρχεία CSV. Εάν δεν έχετε ιδέα να χρησιμοποιήσετε τη csv
λειτουργική μονάδα, ρίξτε μια ματιά στο σεμινάριό μας για το Python CSV: Διαβάστε και γράψτε αρχεία CSV
Βασική χρήση του csv.writer ()
Ας δούμε ένα βασικό παράδειγμα χρήσης csv.
writer
()
για να ανανεώσετε τις υπάρχουσες γνώσεις σας.
Παράδειγμα 1: Γράψτε σε αρχεία CSV με το csv.writer ()
Ας υποθέσουμε ότι θέλουμε να γράψουμε ένα αρχείο CSV με τις ακόλουθες καταχωρίσεις:
SN, Όνομα, Συμβολή 1, Linus Torvalds, Linux Kernel 2, Tim Berners-Lee, World Wide Web 3, Guido van Rossum, Python Programming
Δείτε πώς το κάνουμε.
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"))
Όταν εκτελούμε το παραπάνω πρόγραμμα, δημιουργείται ένα αρχείο innovators.csv στον τρέχοντα κατάλογο εργασίας με τις δεδομένες καταχωρήσεις.
Εδώ, ανοίξαμε το αρχείο innovators.csv σε λειτουργία γραφής χρησιμοποιώντας τη open()
λειτουργία.
Για να μάθετε περισσότερα σχετικά με το άνοιγμα αρχείων στο Python, επισκεφθείτε: Python File Input / Output
Στη συνέχεια, η csv.writer()
συνάρτηση χρησιμοποιείται για τη δημιουργία ενός writer
αντικειμένου. Στη writer.writerow()
συνέχεια, η συνάρτηση χρησιμοποιείται για την εγγραφή μεμονωμένων σειρών στο αρχείο CSV.
Παράδειγμα 2: Σύνταξη πολλαπλών σειρών με συγγραφείς ()
Εάν πρέπει να γράψουμε τα περιεχόμενα της δισδιάστατης λίστας σε ένα αρχείο CSV, δείτε πώς μπορούμε να το κάνουμε.
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)
Η έξοδος του προγράμματος είναι η ίδια όπως στο Παράδειγμα 1 .
Εδώ, η δισδιάστατη λίστα μας μεταφέρεται στη writer.writerows()
συνάρτηση για την εγγραφή του περιεχομένου της λίστας στο αρχείο CSV.
Τώρα ας δούμε πώς μπορούμε να γράψουμε αρχεία CSV σε διαφορετικές μορφές. Στη συνέχεια, θα μάθουμε πώς να προσαρμόζουμε τη csv.writer()
λειτουργία για να τις γράφουμε.
Αρχεία CSV με προσαρμοσμένα διαχωριστικά
Από προεπιλογή, ένα κόμμα χρησιμοποιείται ως οριοθέτης σε ένα αρχείο CSV. Ωστόσο, ορισμένα αρχεία CSV μπορούν να χρησιμοποιούν οριοθέτες εκτός από κόμμα. Λίγα δημοφιλή είναι |
και
.
Ας υποθέσουμε ότι θέλουμε να το χρησιμοποιήσουμε |
ως οριοθέτης στο αρχείο innovators.csv του Παραδείγματος 1 . Για να γράψουμε αυτό το αρχείο, μπορούμε να περάσουμε μια επιπλέον delimiter
παράμετρο στη csv.writer()
συνάρτηση.
Ας πάρουμε ένα παράδειγμα.
Παράδειγμα 3: Σύνταξη αρχείου CSV με διαχωριστικό σωλήνα
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)
Παραγωγή
SN | Όνομα | Συνεισφορά 1 | Linus Torvalds | Linux Kernel 2 | Tim Berners-Lee | World Wide Web 3 | Guido van Rossum | Προγραμματισμός Python
Όπως μπορούμε να δούμε, η προαιρετική παράμετρος delimiter = '|'
βοηθά στον καθορισμό του writer
αντικειμένου που πρέπει να έχει |
το αρχείο CSV ως οριοθέτης.
Αρχεία CSV με εισαγωγικά
Ορισμένα αρχεία CSV έχουν εισαγωγικά γύρω από κάθε μία ή μερικές από τις καταχωρήσεις.
Ας πάρουμε το quotes.csv ως παράδειγμα, με τις ακόλουθες καταχωρίσεις:
"SN"; "Όνομα"; "Αποσπάσματα" 1; "Βούδας"; "Αυτό που πιστεύουμε ότι γινόμαστε" 2; "Mark Twain"; "Ποτέ δεν μετανιώνω για τίποτα που σε έκανε να χαμογελάς" 3; "Oscar Wilde"; "Γίνε ο εαυτός σου" όλοι οι άλλοι έχουν ήδη ληφθεί "
Η χρήση csv.writer()
από προεπιλογή δεν θα προσθέσει αυτά τα αποσπάσματα στις καταχωρήσεις.
Για να τα προσθέσουμε, θα πρέπει να χρησιμοποιήσουμε μια άλλη προαιρετική παράμετρο που ονομάζεται quoting
.
Ας πάρουμε ένα παράδειγμα για το πώς μπορούν να χρησιμοποιηθούν οι τιμές γύρω από τις μη αριθμητικές τιμές και ;
ως οριοθέτες.
Παράδειγμα 4: Γράψτε αρχεία CSV με εισαγωγικά
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)
Παραγωγή
"SN"; "Όνομα"; "Αποσπάσματα" 1; "Βούδας"; "Αυτό που πιστεύουμε ότι γινόμαστε" 2; "Mark Twain"; "Ποτέ δεν μετανιώνω για τίποτα που σε έκανε να χαμογελάς" 3; "Oscar Wilde"; "Γίνε ο εαυτός σου" όλοι οι άλλοι έχουν ήδη ληφθεί "
Εδώ, το αρχείο quotes.csv δημιουργείται στον κατάλογο εργασίας με τις παραπάνω καταχωρήσεις.
Όπως μπορείτε να δείτε, περάσαμε csv.QUOTE_NONNUMERIC
στην quoting
παράμετρο. Είναι μια σταθερά που ορίζεται από την csv
ενότητα.
csv.QUOTE_NONNUMERIC
καθορίζει το writer
αντικείμενο που πρέπει να προστεθούν εισαγωγικά γύρω από τις μη αριθμητικές καταχωρήσεις.
Υπάρχουν 3 άλλες προκαθορισμένες σταθερές που μπορείτε να περάσετε στην quoting
παράμετρο:
csv.QUOTE_ALL
- Καθορίζει τοwriter
αντικείμενο για εγγραφή αρχείου CSV με εισαγωγικά γύρω από όλες τις εγγραφές.csv.QUOTE_MINIMAL
- Καθορίζει τοwriter
αντικείμενο για να παραθέτει μόνο τα πεδία που περιέχουν ειδικούς χαρακτήρες ( οριοθέτης , quotechar ή τυχόν χαρακτήρες στο lineterminator )csv.QUOTE_NONE
- Καθορίζει τοwriter
αντικείμενο που δεν πρέπει να αναφέρεται καμία από τις καταχωρήσεις. Είναι η προεπιλεγμένη τιμή.
Αρχεία CSV με προσαρμοσμένο χαρακτήρα αναφοράς
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.
Προτεινόμενη ανάγνωση: Διαβάστε αρχεία CSV στο Python