{"id":8459,"date":"2023-11-08T18:35:08","date_gmt":"2023-11-08T13:05:08","guid":{"rendered":"https:\/\/python-programs.com\/?p=8459"},"modified":"2023-11-10T12:22:53","modified_gmt":"2023-11-10T06:52:53","slug":"python-data-persistence-csv-module","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/","title":{"rendered":"Python Data Persistence – csv module"},"content":{"rendered":"

Python Data Persistence – csv module<\/h2>\n

The Comma Separated Values (CSV)<\/strong> format is very widely used to import and export data in spreadsheets and RDBMS tables. The csv module, another built-in module in Python\u2019s standard library, presents the functionality to easily convert Python\u2019s sequence object in CSV format and write to a disk file. Conversely, data from CSV files is possible to be brought in Python namespace. The reader and writer classes are defined in this module that performs read\/write operations on CSV files. In addition, this module also has DictReader and DxctWriter classes to work with Python\u2019s dictionary objects.<\/p>\n

The object of the writer class is obtained by the writer () constructor which needs a file object having \u2018w\u2019<\/strong> mode enabled. An optional \u2018dialect\u2019<\/strong> parameter is given to specify the implementation type of CSV protocol, which is by default \u2018excel\u2019 – the format preferred by MS Excel spreadsheet software. We are now in a position to write one or more rows to the file represented by the writer object.<\/p>\n

Example<\/strong><\/p>\n

>>> import csv\r\n>>> data=[('TV', 1 Samsung',25000) , ( 'Comput-\r\ner1 'Dell40000),('Mobile', 'Redmi ',15000)]\r\n> > > file=open (' pricelist .csv' , 'w' , newline='')\r\n>>> obj =csv. writer (file)\r\n>>> #write single row\r\n>>> obj.writerow(data[0])\r\n>>> #write multiple rows\r\n> > > obj.writerows(data [1:])\r\n> > > file . close ( )<\/pre>\n

Note that, open( )<\/strong> function needs the newline=’ ‘<\/strong> parameter to correctly interpret newlines inside quoted fields. The \u2018pricelist.csv\u2019 should be created in the current working directory. Its contents can be verified by opening in any text editor, as per your choice.
\nThe reader object, on the other, hand returns an iterator object of rows in the CSV file. A simple for loop or next() function of an iterator can be used to traverse all rows.<\/p>\n

Example<\/strong><\/p>\n

>>> file=open ('pricelist .csv' , ' r ' newline=' ' )\r\n>>> obj =csv. reader (file)\r\n>>> for row in obj:\r\nprint (row)\r\n['TV', 'Samsung', 25000']\r\n['Computer', 'Dell , '40000']\r\n['Mobile', 'Redmi' '15000']\r\n>>><\/pre>\n

The csv module offers powerful DictWriter and DictReader classes that can deal with dictionary objects. DictWriter<\/strong> maps the sequence of dictionary objects to rows in the CSV file. As always, the DictWriter constructor needs a writable file object. It also needs a fieldnames parameter whose value has to be a list of fields. These fields will be written as a first row in the resultant CSV file. Let us convert a list of tuples, in the above example, to a list of diet objects and send it to csv format using the DictWriter object.<\/p>\n

Example<\/strong><\/p>\n

>>> data=[{'product':'TV', 'brand1:1 Samsung ','price':25000}, {'product':'Computer','br and':'Dell','price':40000},{'product':'Mo\u00acbile ', 'brand' :'Redmi', 'price' :15000 } ]\r\n>>> file=open (' pricelist. csv' , ' w' , newline= ' ')\r\n>>> fields=data [0] .keys()\r\n>>> obj =csv.DictWriter (file,fields)<\/pre>\n

The DictWriter\u2019s write header () method uses fieldnames parameter to write header row in CSV file. Each row following the header contains the keys of each dictionary item.<\/p>\n

Example<\/strong><\/p>\n

>>> obj.writeheader() \r\n>>> obj.writerows(data)\r\n>>> 'file . close ()<\/pre>\n

The resulting \u2018pricelist.csv\u2019 will show data, as follows:<\/p>\n

Example<\/strong><\/p>\n

product,brand,price \r\nTV,Samsung, 2 5000 \r\nComputer,Dell ,4 0000 \r\nMobile,Redmi,15000<\/pre>\n

Reading rows in dictionary formation is easy as well. The DictReader object is obtained from the source CSV file. The object stores strings in the first row in field name attributes. A simple for loop can fetch subsequent rows. However, each row returns an OrderedDict object. Use diet () function to obtain a normal dictionary object out of each row.<\/p>\n

Example<\/strong><\/p>\n

>>> file=open ('pricelist. csvr ,newline='')\r\n>>> obj=csv.DictReader (file)\r\n>>> obj .fieldnames\r\n['product1, 'brand', 'price']\r\n>>> for row in obj:\r\nprint (diet(row))\r\n{'product': 'TV', 'brand': 'Samsung', price': '25000'}\r\n{'product': 'Computer', 'brand' 'Dell ' , ' price' : '40000'}\r\n{'product': 'Mobile', 'brand': Redmi' 'price': ' 15000'}<\/pre>\n

 <\/p>\n","protected":false},"excerpt":{"rendered":"

Python Data Persistence – csv module The Comma Separated Values (CSV) format is very widely used to import and export data in spreadsheets and RDBMS tables. The csv module, another built-in module in Python\u2019s standard library, presents the functionality to easily convert Python\u2019s sequence object in CSV format and write to a disk file. Conversely, …<\/p>\n

Python Data Persistence – csv module<\/span> Read More »<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[5],"tags":[],"yoast_head":"\nPython Data Persistence - csv module - Python Programs<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Data Persistence - csv module - Python Programs\" \/>\n<meta property=\"og:description\" content=\"Python Data Persistence – csv module The Comma Separated Values (CSV) format is very widely used to import and export data in spreadsheets and RDBMS tables. The csv module, another built-in module in Python\u2019s standard library, presents the functionality to easily convert Python\u2019s sequence object in CSV format and write to a disk file. Conversely, … Python Data Persistence – csv module Read More »\" \/>\n<meta property=\"og:url\" content=\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Programs\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/btechgeeks\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-08T13:05:08+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-10T06:52:53+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:site\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prasanna\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https:\/\/python-programs.com\/#organization\",\"name\":\"BTech Geeks\",\"url\":\"https:\/\/python-programs.com\/\",\"sameAs\":[\"https:\/\/www.instagram.com\/btechgeeks\/\",\"https:\/\/www.linkedin.com\/in\/btechgeeks\",\"https:\/\/in.pinterest.com\/btechgeek\/\",\"https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg\",\"https:\/\/www.facebook.com\/btechgeeks\",\"https:\/\/twitter.com\/btech_geeks\"],\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"contentUrl\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"width\":350,\"height\":70,\"caption\":\"BTech Geeks\"},\"image\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\"}},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/python-programs.com\/#website\",\"url\":\"https:\/\/python-programs.com\/\",\"name\":\"Python Programs\",\"description\":\"Python Programs with Examples, How To Guides on Python\",\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/python-programs.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#webpage\",\"url\":\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/\",\"name\":\"Python Data Persistence - csv module - Python Programs\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/#website\"},\"datePublished\":\"2023-11-08T13:05:08+00:00\",\"dateModified\":\"2023-11-10T06:52:53+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/python-programs.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python Data Persistence – csv module\"}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#webpage\"},\"author\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb\"},\"headline\":\"Python Data Persistence – csv module\",\"datePublished\":\"2023-11-08T13:05:08+00:00\",\"dateModified\":\"2023-11-10T06:52:53+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#webpage\"},\"wordCount\":453,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#respond\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb\",\"name\":\"Prasanna\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g\",\"caption\":\"Prasanna\"},\"url\":\"https:\/\/python-programs.com\/author\/prasanna\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Data Persistence - csv module - Python Programs","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/","og_locale":"en_US","og_type":"article","og_title":"Python Data Persistence - csv module - Python Programs","og_description":"Python Data Persistence – csv module The Comma Separated Values (CSV) format is very widely used to import and export data in spreadsheets and RDBMS tables. The csv module, another built-in module in Python\u2019s standard library, presents the functionality to easily convert Python\u2019s sequence object in CSV format and write to a disk file. Conversely, … Python Data Persistence – csv module Read More »","og_url":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/","og_site_name":"Python Programs","article_publisher":"https:\/\/www.facebook.com\/btechgeeks","article_published_time":"2023-11-08T13:05:08+00:00","article_modified_time":"2023-11-10T06:52:53+00:00","twitter_card":"summary_large_image","twitter_creator":"@btech_geeks","twitter_site":"@btech_geeks","twitter_misc":{"Written by":"Prasanna","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Organization","@id":"https:\/\/python-programs.com\/#organization","name":"BTech Geeks","url":"https:\/\/python-programs.com\/","sameAs":["https:\/\/www.instagram.com\/btechgeeks\/","https:\/\/www.linkedin.com\/in\/btechgeeks","https:\/\/in.pinterest.com\/btechgeek\/","https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg","https:\/\/www.facebook.com\/btechgeeks","https:\/\/twitter.com\/btech_geeks"],"logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/","url":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","contentUrl":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","width":350,"height":70,"caption":"BTech Geeks"},"image":{"@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/"}},{"@type":"WebSite","@id":"https:\/\/python-programs.com\/#website","url":"https:\/\/python-programs.com\/","name":"Python Programs","description":"Python Programs with Examples, How To Guides on Python","publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/python-programs.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#webpage","url":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/","name":"Python Data Persistence - csv module - Python Programs","isPartOf":{"@id":"https:\/\/python-programs.com\/#website"},"datePublished":"2023-11-08T13:05:08+00:00","dateModified":"2023-11-10T06:52:53+00:00","breadcrumb":{"@id":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/python-programs.com\/python-data-persistence-csv-module\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/python-programs.com\/"},{"@type":"ListItem","position":2,"name":"Python Data Persistence – csv module"}]},{"@type":"Article","@id":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#article","isPartOf":{"@id":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#webpage"},"author":{"@id":"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb"},"headline":"Python Data Persistence – csv module","datePublished":"2023-11-08T13:05:08+00:00","dateModified":"2023-11-10T06:52:53+00:00","mainEntityOfPage":{"@id":"https:\/\/python-programs.com\/python-data-persistence-csv-module\/#webpage"},"wordCount":453,"commentCount":0,"publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/python-programs.com\/python-data-persistence-csv-module\/#respond"]}]},{"@type":"Person","@id":"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb","name":"Prasanna","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g","caption":"Prasanna"},"url":"https:\/\/python-programs.com\/author\/prasanna\/"}]}},"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8459"}],"collection":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/comments?post=8459"}],"version-history":[{"count":2,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8459\/revisions"}],"predecessor-version":[{"id":9381,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8459\/revisions\/9381"}],"wp:attachment":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/media?parent=8459"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/categories?post=8459"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/tags?post=8459"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}