{"id":1093,"date":"2016-04-11T09:18:42","date_gmt":"2016-04-11T09:18:42","guid":{"rendered":"http:\/\/frowningbear.com\/blog\/?p=1093"},"modified":"2016-04-11T09:18:42","modified_gmt":"2016-04-11T09:18:42","slug":"python-file-reading-and-writing-reference","status":"publish","type":"post","link":"https:\/\/frowningbear.com\/codebase\/2016\/04\/11\/python-file-reading-and-writing-reference\/","title":{"rendered":"Python File Reading and Writing Reference"},"content":{"rendered":"<p>Just my personal reference notes for everything related to reading and writing files in Python.<br \/>\n<!--more--><\/p>\n<pre class=\"wrap:true lang:default decode:true \" >#The open() function returns a stream object, which has methods and attributes for getting information about and manipulating a stream of characters. \nf = open(\"myfile.txt\", \"r\", encoding=\"utf-8\")\n\nprint(type(f)) #<class '_io.TextIOWrapper'>\nprint(f.name)\nprint(f.encoding)\nprint(f.mode)\n\n#calling the stream object's read() method results in a string.\nprint(f.read())\n\n#reading the file again does not raise an exception. Python does not consider reading past end-of-file to be an error; it simply returns an empty string. \nprint(f.read())\n\n#to re-read, the seek() method moves to a specific byte position\nf.seek(0)\n\n#The read() method can take an optional parameter, the number of bytes to read.\nprint(f.read(3))\n\n#subsequent reads will pick up after the previously read bytes\nprint(f.read(1)) #read the 4th byte\n\n#get the current position\nprint(f.tell())\n\nf.seek(0)\n\n#f.readline() reads a single line from the file; a newline character (\\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn\u2019t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\\n', a string containing only a single newline.\nprint(f.readline())\n\n#read the next line\nprint(f.readline())\n\nf.seek(0)\n\n#For reading lines from a file, one at a time, you can loop over the file object.\n#Besides having explicit methods like read(), the stream object is also an iterator which spits out a single line every time you ask for a value. \nfor line in f:\n    #each line is a string\n    print(line, end=\"\") #pass end argument to avoid default new line \n\nf.seek(0)\n\nprint(\"\\n\")\n\n#use the readlines() method to get a list of string values from the file, one string for each line of text. Or use list(f)\nprint(f.readlines())\n\nf.seek(0)\n\nprint(\"\\n\")\n\n#put into variable and print a subset of the list or a specific line\nlines = f.readlines()\nprint(lines[:3])\n\nf.seek(0)\n\n#read the whole file into a string\ncontents = f.read()\n\nprint(\"\\n\")\n\nprint(type(contents)) #<class 'str'>\n\n#the length of the string\nprint(\"\\n\",len(contents))\n\nprint(\"\\n\")\n\nprint(contents)\n\n#contents is a string so we can print a character by index \nprint(contents[5])\n\n#we can loop over each character\nfor char in contents:\n    print(char)\n\nf.close()\n\nf.closed #true\n\n# The keyword 'with' closes the file once access to it is no longer needed\nwith open(\"myfile.txt\", \"r\", encoding=\"utf-8\") as f:\n    print(f.read())\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Just my personal reference notes for everything related to reading and writing files in Python.<\/p>\n","protected":false},"author":2,"featured_media":1098,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[14],"tags":[],"class_list":["post-1093","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/1093","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/comments?post=1093"}],"version-history":[{"count":0,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/posts\/1093\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/media?parent=1093"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/categories?post=1093"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/frowningbear.com\/codebase\/wp-json\/wp\/v2\/tags?post=1093"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}