{"id":1193,"date":"2020-11-13T01:22:56","date_gmt":"2020-11-13T01:22:56","guid":{"rendered":"http:\/\/learnlearn.uk\/alevelcs\/?page_id=1193"},"modified":"2020-11-13T01:33:13","modified_gmt":"2020-11-13T01:33:13","slug":"writing-data-txt-files","status":"publish","type":"page","link":"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/","title":{"rendered":"Writing Data to TXT Files"},"content":{"rendered":"<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">Introduction<\/h2>\n<div class=\"tabcontent\">\n\n<h3>Introduction<\/h3>\n<p>One of the limitations of lists is that when your program terminates you lose all of the data in the list. This is the same for variables and other data structures. If you\u00a0want the data to be kept then you need to save your data to a file and load it again later. This is known as persistent data storage.<\/p>\n<p>The simplest form of persistent data storage in Python is in a text file, using the open() function.<\/p>\n<p><strong>It is great for storing:<\/strong><\/p>\n<div class=\"arconix-list\" data-arconix-icon=\"fa-chevron-circle-right\" data-arconix-color=\"black\">\n<ul>\n<li>Variables (like strings and integers)<\/li>\n<li>Simple 1-dimensional lists (such as a shopping list)<\/li>\n<\/ul>\n<\/div>\n<p><strong>It is not good for:<\/strong><\/p>\n<div class=\"arconix-list\" data-arconix-icon=\"fa-chevron-circle-right\" data-arconix-color=\"black\">\n<ul>\n<li>Dictionaries (<a href=\"http:\/\/www.pitt.edu\/~naraehan\/python2\/pickling.html\">use pickle instead<\/a>)<\/li>\n<li>2 Dimensional lists ( <a href=\"https:\/\/automatetheboringstuff.com\/chapter14\/\">use CSV writer instead<\/a>)<\/li>\n<li>Complex relational data \u00a0(<a href=\"http:\/\/learnlearn.uk\/sql\/\">use a database instead<\/a>)<\/li>\n<\/ul>\n<\/div>\n\n<\/div><h2 class=\"tabtitle\">Reading<\/h2>\n<div class=\"tabcontent\">\n\n<h3>Reading\u00a0data from a text file<\/h3>\n<p>Loading data from a file is easy, just specify the file using the open() command. Then read the data in to a list or variable.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; border: solid gray; border-width: .1em .1em .1em .8em; padding: .2em .6em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\">#Open a file and print out all the contents.<\/span>\r\n\r\nf <span style=\"color: #333333;\">=<\/span> <span style=\"color: #007020;\">open<\/span>(<span style=\"background-color: #fff0f0;\">\"myfile.txt\"<\/span>,<span style=\"background-color: #fff0f0;\">\"r\"<\/span>)\r\n<span style=\"color: #008800; font-weight: bold;\">for<\/span> line <span style=\"color: #000000; font-weight: bold;\">in<\/span> f:\r\n    <span style=\"color: #008800; font-weight: bold;\">print<\/span>(<span style=\"background-color: #fff0f0;\">\"line)<\/span>\r\n\r\n<span style=\"color: #888888;\">#Read one line from the file and save it to a variable.<\/span>\r\n\r\nf <span style=\"color: #333333;\">=<\/span> <span style=\"color: #007020;\">open<\/span>(<span style=\"background-color: #fff0f0;\">\"highscore.txt\"<\/span>,<span style=\"background-color: #fff0f0;\">\"r\"<\/span>)\r\nscore <span style=\"color: #333333;\">=<\/span> f<span style=\"color: #333333;\">.<\/span>readline()\r\n\r\n<span style=\"color: #888888;\">#Read the whole file in to a list.<\/span>\r\n\r\nf <span style=\"color: #333333;\">=<\/span> <span style=\"color: #007020;\">open<\/span>(<span style=\"background-color: #fff0f0;\">\"shopping.txt\"<\/span>,<span style=\"background-color: #fff0f0;\">\"r\"<\/span>)\r\nshoppingList <span style=\"color: #333333;\">=<\/span> []\r\n<span style=\"color: #008800; font-weight: bold;\">for<\/span> line <span style=\"color: #000000; font-weight: bold;\">in<\/span> f:\r\n    shoppingList<span style=\"color: #333333;\">.<\/span>append(line)\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p><strong>Tutorial Video<\/strong><\/p>\n<p><iframe loading=\"lazy\" src=\"https:\/\/www.youtube.com\/embed\/6BfmLoUGGIo\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\" data-mce-fragment=\"1\"><\/iframe><br \/>\n<a href=\"https:\/\/drive.google.com\/file\/d\/0B4M7J3ubGpimeUZxMEFTYVhGV0U\/view\">Can&#8217;t access YouTube? Click here for the Google Drive version<\/a><\/p>\n<p>&nbsp;<\/p>\n\n<\/div><h2 class=\"tabtitle\">Writing Data To A File<\/h2>\n<div class=\"tabcontent\">\n\n<h3>Writing data to \u00a0a text file<\/h3>\n<p>When you write data to a text file the process is quite simple. In Python you have two options for how you want to write to the file:<\/p>\n<ul>\n<li>&#8216;a&#8217; &#8211;\u00a0 Append mode. This adds the data to the end of the file.<\/li>\n<li>&#8216;w&#8217; &#8211; Write mode. This deletes all existing data in the file and overwrites it with the new data.<\/li>\n<\/ul>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; border: solid gray; border-width: .1em .1em .1em .8em; padding: .2em .6em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\">#Here we try to append to the weights.txt file. If it doesn't exist we create it instead.<\/span>\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">try<\/span>:\r\n    f <span style=\"color: #333333;\">=<\/span> <span style=\"color: #007020;\">open<\/span>(<span style=\"background-color: #fff0f0;\">'weights.txt'<\/span>,<span style=\"background-color: #fff0f0;\">\"a\"<\/span>)  <span style=\"color: #888888;\">#To append(add) to  a file we use \"a\" instead of \"w\"<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">except<\/span>:\r\n    f <span style=\"color: #333333;\">=<\/span> <span style=\"color: #007020;\">open<\/span>(<span style=\"background-color: #fff0f0;\">'weights.txt'<\/span>,<span style=\"background-color: #fff0f0;\">\"w\"<\/span>)\r\n\r\n\r\nweight <span style=\"color: #333333;\">=<\/span> <span style=\"color: #007020;\">input<\/span>(<span style=\"background-color: #fff0f0;\">\"How much do you weigh this week (Kgs)?\"<\/span>)\r\n<span style=\"color: #888888;\">#We need to add the newline character (\\n) so that each weight is added to a new line.<\/span>\r\nf<span style=\"color: #333333;\">.<\/span>write(weight <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\"<\/span><span style=\"color: #666666; font-weight: bold; background-color: #fff0f0;\">\\n<\/span><span style=\"background-color: #fff0f0;\">\"<\/span>) \r\n\r\nf<span style=\"color: #333333;\">.<\/span>close() <span style=\"color: #888888;\">#This line is important! The file won't save until you do this!<\/span>\r\n\r\n<span style=\"color: #008800; font-weight: bold;\">print<\/span>(<span style=\"background-color: #fff0f0;\">\"We have added \"<\/span><span style=\"color: #333333;\">+<\/span>weight<span style=\"color: #333333;\">+<\/span><span style=\"background-color: #fff0f0;\">\"Kg to the file.\"<\/span>)\r\n<\/pre>\n<\/div>\n<p><strong>Tutorial Video<\/strong><\/p>\n<p><a href=\"https:\/\/drive.google.com\/open?id=0B4M7J3ubGpimaFhWYzZSMzJBMHc\">Can&#8217;t access YouTube? Click here for the Google Drive Version<\/a><br \/>\n<iframe loading=\"lazy\" src=\"https:\/\/www.youtube.com\/embed\/RZV2Pn-MSLI\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\" data-mce-fragment=\"1\"><\/iframe><\/p>\n<p><strong>Overwrite Mode ( Replace contents)<\/strong><\/p>\n<p>Saving data is easy. If you want to overwrite previously saved data use the &#8216;w&#8217; parameter.<\/p>\n<p><strong>Append Mode (Adding to the contents)<\/strong><\/p>\n<p>To add to a file use the &#8216;a&#8217; parameter instead of &#8216;w&#8217;. Don&#8217;t forget to add a newline \u00a0(\\n) to the end of your line, so that each item is added to a new line<\/p>\n<p>&nbsp;<\/p>\n\n<\/div><h2 class=\"tabtitle\">Resources<\/h2>\n<div class=\"tabcontent\">\n\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Introduction One of the limitations of lists is that when your program terminates you lose all of the data in the list. This is the same for variables and other data structures. If you\u00a0want the data to be kept then you need to save your data to a file and load it again later. This&hellip;&nbsp;<a href=\"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/\" class=\"\" rel=\"bookmark\">Read More &raquo;<span class=\"screen-reader-text\">Writing Data to TXT Files<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"neve_meta_sidebar":"","neve_meta_container":"","neve_meta_enable_content_width":"","neve_meta_content_width":70,"neve_meta_title_alignment":"","neve_meta_author_avatar":"","neve_post_elements_order":"","neve_meta_disable_header":"","neve_meta_disable_footer":"","neve_meta_disable_title":""},"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.6 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Writing Data to TXT Files - A Level Computer Science<\/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:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/\" \/>\n<meta property=\"og:locale\" content=\"en_GB\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Writing Data to TXT Files - A Level Computer Science\" \/>\n<meta property=\"og:description\" content=\"Introduction One of the limitations of lists is that when your program terminates you lose all of the data in the list. This is the same for variables and other data structures. If you\u00a0want the data to be kept then you need to save your data to a file and load it again later. This&hellip;&nbsp;Read More &raquo;Writing Data to TXT Files\" \/>\n<meta property=\"og:url\" content=\"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/\" \/>\n<meta property=\"og:site_name\" content=\"A Level Computer Science\" \/>\n<meta property=\"article:modified_time\" content=\"2020-11-13T01:33:13+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Estimated reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/\",\"url\":\"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/\",\"name\":\"Writing Data to TXT Files - A Level Computer Science\",\"isPartOf\":{\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/#website\"},\"datePublished\":\"2020-11-13T01:22:56+00:00\",\"dateModified\":\"2020-11-13T01:33:13+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/#breadcrumb\"},\"inLanguage\":\"en-GB\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"A Level Computer Science Home\",\"item\":\"https:\/\/learnlearn.uk\/alevelcs\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Writing Data to TXT Files\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/#website\",\"url\":\"https:\/\/learnlearn.uk\/alevelcs\/\",\"name\":\"A Level Computer Science\",\"description\":\"CIE Specification\",\"publisher\":{\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/learnlearn.uk\/alevelcs\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-GB\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/#organization\",\"name\":\"A Level Computer Science\",\"url\":\"https:\/\/learnlearn.uk\/alevelcs\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-GB\",\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/learnlearn.uk\/alevelcs\/wp-content\/uploads\/sites\/20\/2019\/09\/LearnLearnLogowhite.png\",\"contentUrl\":\"https:\/\/learnlearn.uk\/alevelcs\/wp-content\/uploads\/sites\/20\/2019\/09\/LearnLearnLogowhite.png\",\"width\":710,\"height\":98,\"caption\":\"A Level Computer Science\"},\"image\":{\"@id\":\"https:\/\/learnlearn.uk\/alevelcs\/#\/schema\/logo\/image\/\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Writing Data to TXT Files - A Level Computer Science","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:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/","og_locale":"en_GB","og_type":"article","og_title":"Writing Data to TXT Files - A Level Computer Science","og_description":"Introduction One of the limitations of lists is that when your program terminates you lose all of the data in the list. This is the same for variables and other data structures. If you\u00a0want the data to be kept then you need to save your data to a file and load it again later. This&hellip;&nbsp;Read More &raquo;Writing Data to TXT Files","og_url":"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/","og_site_name":"A Level Computer Science","article_modified_time":"2020-11-13T01:33:13+00:00","twitter_card":"summary_large_image","twitter_misc":{"Estimated reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/","url":"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/","name":"Writing Data to TXT Files - A Level Computer Science","isPartOf":{"@id":"https:\/\/learnlearn.uk\/alevelcs\/#website"},"datePublished":"2020-11-13T01:22:56+00:00","dateModified":"2020-11-13T01:33:13+00:00","breadcrumb":{"@id":"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/#breadcrumb"},"inLanguage":"en-GB","potentialAction":[{"@type":"ReadAction","target":["https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/learnlearn.uk\/alevelcs\/writing-data-txt-files\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"A Level Computer Science Home","item":"https:\/\/learnlearn.uk\/alevelcs\/"},{"@type":"ListItem","position":2,"name":"Writing Data to TXT Files"}]},{"@type":"WebSite","@id":"https:\/\/learnlearn.uk\/alevelcs\/#website","url":"https:\/\/learnlearn.uk\/alevelcs\/","name":"A Level Computer Science","description":"CIE Specification","publisher":{"@id":"https:\/\/learnlearn.uk\/alevelcs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/learnlearn.uk\/alevelcs\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-GB"},{"@type":"Organization","@id":"https:\/\/learnlearn.uk\/alevelcs\/#organization","name":"A Level Computer Science","url":"https:\/\/learnlearn.uk\/alevelcs\/","logo":{"@type":"ImageObject","inLanguage":"en-GB","@id":"https:\/\/learnlearn.uk\/alevelcs\/#\/schema\/logo\/image\/","url":"https:\/\/learnlearn.uk\/alevelcs\/wp-content\/uploads\/sites\/20\/2019\/09\/LearnLearnLogowhite.png","contentUrl":"https:\/\/learnlearn.uk\/alevelcs\/wp-content\/uploads\/sites\/20\/2019\/09\/LearnLearnLogowhite.png","width":710,"height":98,"caption":"A Level Computer Science"},"image":{"@id":"https:\/\/learnlearn.uk\/alevelcs\/#\/schema\/logo\/image\/"}}]}},"rttpg_featured_image_url":null,"rttpg_author":{"display_name":"learnlearnadmin","author_link":"https:\/\/learnlearn.uk\/alevelcs\/author\/learnlearnadmin\/"},"rttpg_comment":0,"rttpg_category":null,"rttpg_excerpt":"Introduction One of the limitations of lists is that when your program terminates you lose all of the data in the list. This is the same for variables and other data structures. If you\u00a0want the data to be kept then you need to save your data to a file and load it again later. This&hellip;&nbsp;Read&hellip;","_links":{"self":[{"href":"https:\/\/learnlearn.uk\/alevelcs\/wp-json\/wp\/v2\/pages\/1193"}],"collection":[{"href":"https:\/\/learnlearn.uk\/alevelcs\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/learnlearn.uk\/alevelcs\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/learnlearn.uk\/alevelcs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnlearn.uk\/alevelcs\/wp-json\/wp\/v2\/comments?post=1193"}],"version-history":[{"count":9,"href":"https:\/\/learnlearn.uk\/alevelcs\/wp-json\/wp\/v2\/pages\/1193\/revisions"}],"predecessor-version":[{"id":1203,"href":"https:\/\/learnlearn.uk\/alevelcs\/wp-json\/wp\/v2\/pages\/1193\/revisions\/1203"}],"wp:attachment":[{"href":"https:\/\/learnlearn.uk\/alevelcs\/wp-json\/wp\/v2\/media?parent=1193"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}