इस ट्यूटोरियल में, हम उदाहरणों की मदद से पायथन में CSV फ़ाइलों को पढ़ना और लिखना सीखेंगे।
एक CSV (कोमा सेपरेटेड वैल्यूज़) प्रारूप सारणीबद्ध डेटा को संग्रहीत करने के सबसे सरल और सामान्य तरीकों में से एक है। CSV फ़ाइल का प्रतिनिधित्व करने के लिए, इसे .csv फ़ाइल एक्सटेंशन के साथ सहेजा जाना चाहिए ।
आइए एक उदाहरण लेते हैं:
यदि आप उप-पाठ जैसे पाठ संपादक का उपयोग करके उपरोक्त CSV फ़ाइल खोलते हैं, तो आप देखेंगे:
एसएन, नाम, शहर 1, माइकल, न्यू जर्सी 2, जैक, कैलिफोर्निया
जैसा कि आप देख सकते हैं, CSV फ़ाइल के तत्व अल्पविराम द्वारा अलग किए जाते हैं। यहाँ, ,
एक सीमांकक है।
आपकी आवश्यकताओं के अनुसार आपका कोई भी चरित्र हो सकता है।
नोट: सीएसवी मॉड्यूल का उपयोग अन्य फ़ाइल एक्सटेंशन (जैसे: .txt ) के लिए भी किया जा सकता है जब तक कि उनकी सामग्री उचित संरचना में न हो।
पायथन में सीएसवी फाइलों के साथ काम करना
जबकि हम open()
पायथन में CSV फ़ाइलों के साथ काम करने के लिए अंतर्निहित फ़ंक्शन का उपयोग कर सकते हैं , एक समर्पित csv
मॉड्यूल है जो CSV फ़ाइलों के साथ काम करना बहुत आसान बनाता है।
इससे पहले कि हम csv
मॉड्यूल के तरीकों का उपयोग कर सकें , हमें पहले उपयोग करके मॉड्यूल को आयात करना होगा:
import csv
CSV फ़ाइलों को CSV.reader () का उपयोग करके पढ़ना
पायथन में एक सीएसवी फ़ाइल पढ़ने के लिए, हम csv.reader()
फ़ंक्शन का उपयोग कर सकते हैं । मान लीजिए कि हमारे पास मौजूदा प्रविष्टियों में People.csvcsv
नाम की एक फ़ाइल है जिसमें निम्नलिखित प्रविष्टियाँ हैं।
नाम | आयु | पेशा |
जैक | २३ | चिकित्सक |
मिलर | २२ | इंजीनियर |
चलिए इस फ़ाइल को पढ़ते हैं csv.reader()
:
उदाहरण 1: कोमा Delimiter होने CSV पढ़ें
import csv with open('people.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
आउटपुट
('नाम', 'आयु', 'प्रोफेशन') ('जैक', '23', 'डॉक्टर') ('मिलर', '22', 'इंजीनियर')
यहाँ, हमने पठन मोड में People.csv फ़ाइल का उपयोग करके खोला है :
with open('people.csv', 'r') as file:…
पायथन में फाइलें खोलने के बारे में अधिक जानने के लिए, यहां जाएं: पायथन फाइल इनपुट / आउटपुट
फिर, csv.reader()
फ़ाइल को पढ़ने के लिए उपयोग किया जाता है, जो एक पुनरावृत्त reader
वस्तु देता है।
reader
वस्तु तो एक का उपयोग कर दोहराया है for
प्रत्येक पंक्ति की सामग्री मुद्रित करने के लिए पाश।
उपरोक्त उदाहरण में, हम csv.reader()
CSV फ़ाइलों के लिए डिफ़ॉल्ट मोड में फ़ंक्शन का उपयोग कर रहे हैं जिसमें अल्पविराम सीमांकक है।
हालाँकि, फ़ंक्शन बहुत अधिक अनुकूलन योग्य है।
मान लीजिए कि हमारी CSV फ़ाइल टैब को सीमांकक के रूप में उपयोग कर रही थी । ऐसी फ़ाइलों को पढ़ने के लिए, हम csv.reader()
फ़ंक्शन के लिए वैकल्पिक पैरामीटर पास कर सकते हैं । एक उदाहरण लेते हैं।
उदाहरण 2: टैब Delimiter वाले CSV फ़ाइल पढ़ें
import csv with open('people.csv', 'r',) as file: reader = csv.reader(file, delimiter = ' ') for row in reader: print(row)
delimiter = ' '
उपर्युक्त उदाहरण में वैकल्पिक पैरामीटर पर ध्यान दें ।
csv.reader()
फ़ंक्शन का पूरा सिंटैक्स है:
csv.reader(csvfile, dialect='excel', **optional_parameters)
जैसा कि आप सिंटैक्स से देख सकते हैं, हम csv.reader()
फ़ंक्शन के लिए बोली पैरामीटर भी पास कर सकते हैं । dialect
पैरामीटर हमें समारोह और अधिक लचीला बनाने के लिए अनुमति देता है। अधिक जानने के लिए, जाएँ: पायथन में CSV फ़ाइलों को पढ़ना।
CSV फ़ाइलों को CSV.writer () का उपयोग करके लिखना
पायथन में एक सीएसवी फ़ाइल लिखने के लिए, हम csv.writer()
फ़ंक्शन का उपयोग कर सकते हैं ।
csv.writer()
समारोह एक रिटर्न writer
उद्देश्य यह है कि एक सीमांकित स्ट्रिंग में धर्मान्तरित उपयोगकर्ता के डाटा। इस स्ट्रिंग को बाद में writerow()
फ़ंक्शन का उपयोग करके CSV फ़ाइलों में लिखने के लिए उपयोग किया जा सकता है । एक उदाहरण लेते हैं।
उदाहरण 3: CSV फ़ाइल में लिखें
import csv with open('protagonist.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(("SN", "Movie", "Protagonist")) writer.writerow((1, "Lord of the Rings", "Frodo Baggins")) writer.writerow((2, "Harry Potter", "Harry Potter"))
जब हम उपरोक्त प्रोग्राम चलाते हैं, तो निम्नलिखित सामग्री के साथ एक नायक .csv फ़ाइल बनाई जाती है:
एसएन, मूवी, नायक 1, लॉर्ड ऑफ द रिंग्स, फ्रोडो बैगिन्स 2, हैरी पॉटर, हैरी पॉटर
उपरोक्त कार्यक्रम में, हमने फ़ाइल को लेखन मोड में खोला है।
फिर, हमने प्रत्येक पंक्ति को एक सूची के रूप में पारित किया है। इन सूचियों को एक सीमांकित स्ट्रिंग में परिवर्तित किया जाता है और CSV फ़ाइल में लिखा जाता है।
उदाहरण 4: लेखक के साथ कई पंक्तियाँ लिखना ()
अगर हमें 2-आयामी सूची की सामग्री को CSV फ़ाइल में लिखने की आवश्यकता है, तो यहां बताया गया है कि हम यह कैसे कर सकते हैं।
import csv csv_rowlist = (("SN", "Movie", "Protagonist"), (1, "Lord of the Rings", "Frodo Baggins"), (2, "Harry Potter", "Harry Potter")) with open('protagonist.csv', 'w') as file: writer = csv.writer(file) writer.writerows(csv_rowlist)
The output of the program is the same as in Example 3.
Here, our 2-dimensional list is passed to the writer.writerows()
method to write the content of the list to the CSV file.
Example 5: Writing to a CSV File with Tab Delimiter
import csv with open('protagonist.csv', 'w') as file: writer = csv.writer(file, delimiter = ' ') writer.writerow(("SN", "Movie", "Protagonist")) writer.writerow((1, "Lord of the Rings", "Frodo Baggins")) writer.writerow((2, "Harry Potter", "Harry Potter"))
Notice the optional parameter delimiter = ' '
in the csv.writer()
function.
The complete syntax of the csv.writer()
function is:
csv.writer(csvfile, dialect='excel', **optional_parameters)
Similar to csv.reader()
, you can also pass dialect parameter the csv.writer()
function to make the function much more customizable. To learn more, visit: Writing CSV files in Python
Python csv.DictReader() Class
The objects of a csv.DictReader()
class can be used to read a CSV file as a dictionary.
Example 6: Python csv.DictReader()
Suppose we have the same file people.csv as in Example 1.
Name | Age | Profession |
Jack | 23 | Doctor |
Miller | 22 | Engineer |
Let's see how csv.DictReader()
can be used.
import csv with open("people.csv", 'r') as file: csv_file = csv.DictReader(file) for row in csv_file: print(dict(row))
Output
('Name': 'Jack', ' Age': ' 23', ' Profession': ' Doctor') ('Name': 'Miller', ' Age': ' 22', ' Profession': ' Engineer')
As we can see, the entries of the first row are the dictionary keys. And, the entries in the other rows are the dictionary values.
Here, csv_file is a csv.DictReader()
object. The object can be iterated over using a for
loop. The csv.DictReader()
returned an OrderedDict
type for each row. That's why we used dict()
to convert each row to a dictionary.
Notice that, we have explicitly used the dict() method to create dictionaries inside the for
loop.
print(dict(row))
Note: Starting from Python 3.8, csv.DictReader() returns a dictionary for each row, and we do not need to use dict()
explicitly.
The full syntax of the csv.DictReader()
class is:
csv.DictReader(file, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
To learn more about it in detail, visit: Python csv.DictReader() class
Python csv.DictWriter() Class
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))
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
Using the Pandas library to Handle CSV files
Pandas is a popular data science library in Python for data manipulation and analysis. If we are working with huge chunks of data, it's better to use pandas to handle CSV files for ease and efficiency.
Before we can use pandas, we need to install it. To learn more, visit: How to install Pandas?
Once we install it, we can import Pandas as:
import pandas as pd
To read the CSV file using pandas, we can use the read_csv()
function.
import pandas as pd pd.read_csv("people.csv")
इधर, कार्यक्रम पढ़ता people.csv वर्तमान निर्देशिका से।
CSV फ़ाइल लिखने के लिए, हमें to_csv()
एक DataFrame के फ़ंक्शन को कॉल करना होगा।
import pandas as pd # creating a data frame df = pd.DataFrame((('Jack', 24), ('Rose', 22)), columns = ('Name', 'Age')) # writing data frame to a CSV file df.to_csv('person.csv')
यहां, हमने pd.DataFrame()
विधि का उपयोग करके एक डाटाफ्रेम बनाया है । फिर, to_csv()
इस ऑब्जेक्ट के लिए फ़ंक्शन को person.csv में लिखने के लिए कहा जाता है ।
अधिक जानने के लिए, यहां जाएं:
- अजगर pandas.read_csv (आधिकारिक साइट)
- पायथन पंडों.पांडस.डताफ्रेम.तो_स्कव (आधिकारिक साइट)