पायथन में सीएसवी फाइलें लिखना

इस ट्यूटोरियल में, हम उदाहरणों की मदद से पायथन में विभिन्न प्रारूपों के साथ सीएसवी फाइलें लिखना सीखेंगे।

हम csvइस कार्य के लिए विशेष रूप से पायथन में निर्मित मॉड्यूल का उपयोग करने जा रहे हैं । लेकिन पहले, हमें मॉड्यूल को आयात करना होगा:

 import csv 

हमने csvCSV फ़ाइलों को पढ़ने और लिखने के लिए मॉड्यूल का उपयोग करने की मूल बातें पहले ही कवर कर ली हैं। यदि आपके पास csvमॉड्यूल का उपयोग करने का कोई विचार नहीं है , तो हमारे ट्यूटोरियल को पाइथन CSV पर देखें: CSV फ़ाइलों को पढ़ें और लिखें

Csv.writer का मूल उपयोग ()

आइए csv.writer()अपने मौजूदा ज्ञान को ताज़ा करने के लिए उपयोग करने के एक मूल उदाहरण को देखें ।

उदाहरण 1: CSV फ़ाइलों को csv.writer () के साथ लिखें

मान लीजिए कि हम निम्नलिखित प्रविष्टियों के साथ एक सीएसवी फ़ाइल लिखना चाहते हैं:

 एसएन, नाम, योगदान 1, लिनुस टोरवाल्ड्स, लिनक्स कर्नेल 2, टिम बर्नर्स-ली, वर्ल्ड वाइड वेब 3, गुइडो वैन रोसुम, पायथन प्रोग्रामिंग 

यहाँ हम इसे कैसे करते हैं।

 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 फ़ाइल बनाई जाती है।

यहां, हमने फ़ंक्शन का उपयोग करके इनोवेटर्स. csv फ़ाइल को लेखन मोड में खोला है open()

पायथन में फाइलें खोलने के बारे में अधिक जानने के लिए, यहां जाएं: पायथन फाइल इनपुट / आउटपुट

अगला, ऑब्जेक्ट csv.writer()बनाने के लिए फ़ंक्शन का उपयोग किया जाता है writerwriter.writerow()समारोह तो CSV फ़ाइल के लिए एकल पंक्तियों को लिखने के लिए प्रयोग किया जाता है।

उदाहरण 2: लेखक के साथ एकाधिक पंक्तियाँ लिखना ()

अगर हमें 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 में समान है ।

यहां, हमारी 2-आयामी सूची को writer.writerows()CSV फ़ाइल में सूची की सामग्री लिखने के लिए फ़ंक्शन को पास किया गया है ।

अब देखते हैं कि हम CSV फ़ाइलों को विभिन्न प्रारूपों में कैसे लिख सकते हैं। फिर हम csv.writer()उन्हें लिखने के लिए फ़ंक्शन को कस्टमाइज़ करना सीखेंगे ।

CSV फ़ाइलें कस्टम डेलीमीटर के साथ

डिफ़ॉल्ट रूप से, CSV फ़ाइल में एक अल्पविराम को एक सीमांकक के रूप में उपयोग किया जाता है। हालांकि, कुछ CSV फाइलें अल्पविराम के अलावा अन्य सीमांकक का उपयोग कर सकती हैं। कुछ लोकप्रिय हैं |और

मान लीजिए कि हम उदाहरण 1| के innovators.csv फ़ाइल में एक सीमांकक के रूप में उपयोग करना चाहते हैं । इस फ़ाइल को लिखने के लिए, हम फ़ंक्शन के लिए एक अतिरिक्त पैरामीटर पास कर सकते हैं ।delimitercsv.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) 

आउटपुट

 एस.एन. नाम 

जैसा कि हम देख सकते हैं, वैकल्पिक पैरामीटर delimiter = '|'उस writerऑब्जेक्ट को निर्दिष्ट करने में मदद करता है जो सीएसएमवी फ़ाइल को |सीमांकक के रूप में होना चाहिए ।

CSV फ़ाइलें उद्धरण के साथ

कुछ CSV फ़ाइलों में प्रत्येक या कुछ प्रविष्टियों के आसपास उद्धरण हैं।

आइए , निम्न प्रविष्टियों के साथ एक उदाहरण के रूप में quotes.csv लेते हैं:

 "एसएन"; "नाम"; "उद्धरण" 1; "बुद्ध"; "हम जो सोचते हैं हम" 2 "; मार्क ट्वेन"; "कभी भी किसी भी बात पर पछतावा न करें जिससे आप मुस्कुराए" 3; "ऑस्कर वाइल्ड"; "स्वयं बनें बाकी सभी पहले से लिए जा चुकें" 

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) 

आउटपुट

 "एसएन"; "नाम"; "उद्धरण" 1; "बुद्ध"; "हम जो सोचते हैं हम" 2 "; मार्क ट्वेन"; "कभी भी किसी भी बात पर पछतावा न करें जिससे आप मुस्कुराए" 3; "ऑस्कर वाइल्ड"; "स्वयं बनें बाकी सभी पहले से लिए जा चुकें" 

यहां, उपरोक्त प्रविष्टियों के साथ कार्य निर्देशिका में quot.csv फ़ाइल बनाई गई है।

जैसा कि आप देख सकते हैं, हम पैरामीटर csv.QUOTE_NONNUMERICको पास कर चुके हैं quoting। यह csvमॉड्यूल द्वारा परिभाषित एक स्थिर है ।

csv.QUOTE_NONNUMERICwriterऑब्जेक्ट को निर्दिष्ट करता है कि गैर-संख्यात्मक प्रविष्टियों के आसपास उद्धरण जोड़े जाने चाहिए।

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

अनुशंसित पढ़ना: पायथन में सीएसवी फाइलें पढ़ें

दिलचस्प लेख...