1"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9410],{3905:(e,t,n)=>{n.d(t,{Zo:()=>d,kt:()=>m});var a=n(67294);function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function o(e,t){if(null==e)return{};var n,a,i=function(e,t){if(null==e)return{};var n,a,i={},r=Object.keys(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var s=a.createContext({}),p=function(e){var t=a.useContext(s),n=t;return e&&(n="function"==typeof e?e(t):l(l({},t),e)),n},d=function(e){var t=p(e.components);return a.createElement(s.Provider,{value:t},e.children)},h="mdxType",f={inlineCode:"code",wrapper:function(e){var t=e.children;return a.createElement(a.Fragment,{},t)}},u=a.forwardRef((function(e,t){var n=e.components,i=e.mdxType,r=e.originalType,s=e.parentName,d=o(e,["components","mdxType","originalType","parentName"]),h=p(n),u=i,m=h["".concat(s,".").concat(u)]||h[u]||f[u]||r;return n?a.createElement(m,l(l({ref:t},d),{},{components:n})):a.createElement(m,l({ref:t},d))}));function m(e,t){var n=arguments,i=t&&t.mdxType;if("string"==typeof e||i){var r=n.length,l=new Array(r);l[0]=u;var o={};for(var s in t)hasOwnProperty.call(t,s)&&(o[s]=t[s]);o.originalType=e,o[h]="string"==typeof e?e:i,l[1]=o;for(var p=2;p<r;p++)l[p]=n[p];return a.createElement.apply(null,l)}return a.createElement.apply(null,n)}u.displayName="MDXCreateElement"},84394:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>s,contentTitle:()=>l,default:()=>h,frontMatter:()=>r,metadata:()=>o,toc:()=>p});var a=n(87462),i=(n(67294),n(3905));const r={title:"Section 04 (Jared Yeager)"},l="File I/O",o={unversionedId:"Files/Jared/index",id:"Files/Jared/index",title:"Section 04 (Jared Yeager)",description:"Files are containers for storing information that live on our computers.",source:"@site/main/lectures/15_Files/Jared/index.md",sourceDirName:"15_Files/Jared",slug:"/Files/Jared/",permalink:"/main/lectures/Files/Jared/",draft:!1,tags:[],version:"current",frontMatter:{title:"Section 04 (Jared Yeager)"},sidebar:"tutorialSidebar",previous:{title:"Lec 15 Files",permalink:"/main/lectures/Files/"},next:{title:"Lec 16 CSV Files",permalink:"/main/lectures/CSV_Files/"}},s={},p=[{value:"Basic I/O",id:"basic-io",level:2},{value:"<code>open(file_name, mode)</code>",id:"openfile_name-mode",level:3},{value:"<code>.close()</code>",id:"close",level:3},{value:"<code>.read()</code>",id:"read",level:3},{value:"<code>.write(content)</code>",id:"writecontent",level:3},{value:"Write vs. Append",id:"write-vs-append",level:3},{value:"<code>with</code> and <code>as</code>",id:"with-and-as",level:3},{value:"Files in Other Places",id:"files-in-other-places",level:2},{value:"Directory Hierarchy",id:"directory-hierarchy",level:3},{value:"Children",id:"children",level:3},{value:"Parent",id:"parent",level:3}],d={toc:p};function h(e){let{components:t,...n}=e;return(0,i.kt)("wrapper",(0,a.Z)({},d,n,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"file-io"},"File I/O"),(0,i.kt)("p",null,"Files are containers for storing information that live on our computers.\n(And I/O just stands for Input/Output.)\nThat definition isn't very elucidating.\nMore intuitively, they are bundles of data, be that text, numbers, formatting information,\netc."),(0,i.kt)("p",null,"The ability to store information beyond the life of our programs can be quite useful.\nSome things files help with:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Giving lots of automatic input:\nInstead of typing a bunch of input and capturing it with the ",(0,i.kt)("inlineCode",{parentName:"li"},"input()")," function,\nwe can write all that input in a file and have the program read that file."),(0,i.kt)("li",{parentName:"ul"},"Having non-hard-coded data structures:\nImagine our program has some big lookup table in it.\nInstead of hard-coding it in the python script, we can have the information written in a file.\nThe script could then load and read that file to build the lookup table.\nThis makes it a lot easier to edit that table in the future,\nand makes the code more modular (easier to swap out parts without breaking other parts)."),(0,i.kt)("li",{parentName:"ul"},"Saving and loading information:\nIf your program wants some information to persist\nacross runs of the program, it can write information to a file\nand load it again when re-launched. For instance, saving progress in a video-game."),(0,i.kt)("li",{parentName:"ul"},"Working with new types of stuff:\nFiles have many different types.\nSo while we will be exploring text and spreadsheet-like file types,\nfiles give us the ability to work with things like images, audio, and video.")),(0,i.kt)("p",null,"By the way, given that code that uses files needs those files to exist in\na reference-able manner, like with modules, the code examples\nfor this lecture can't really be made in a web-runnable way."),(0,i.kt)("h2",{id:"basic-io"},"Basic I/O"),(0,i.kt)("p",null,"For our purposes, there are 4 basic things we will do with files:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"Open them: We need to open files before we can do anything with them."),(0,i.kt)("li",{parentName:"ul"},"Close them: We should close files when we are done with them."),(0,i.kt)("li",{parentName:"ul"},"Read from them: We may want to read the contents of a file."),(0,i.kt)("li",{parentName:"ul"},"Write to them: We may want to write content to a file.")),(0,i.kt)("p",null,"There are aptly named functions for each of these."),(0,i.kt)("p",null,"As an example that uses all of these, we'll aim to read a\nfile named ",(0,i.kt)("inlineCode",{parentName:"p"},"words.txt"),", reverse the lines of that file, and\nwrite those to a file named ",(0,i.kt)("inlineCode",{parentName:"p"},"rev_words.txt"),"."),(0,i.kt)("p",null,"If you want to follow along, I recommend making/opening a sandbox project and\nmaking a file named ",(0,i.kt)("inlineCode",{parentName:"p"},"words.txt"),". The contents of my ",(0,i.kt)("inlineCode",{parentName:"p"},"words.txt")," for testing are:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"}
1,"Apple\nBanana\nCherry\nDurian\n")),(0,i.kt)("h3",{id:"openfile_name-mode"},(0,i.kt)("inlineCode",{parentName:"h3"},"open(file_name, mode)")),(0,i.kt)("p",null,"The first step when working with files is to open the file.\nThe function for this is the ",(0,i.kt)("inlineCode",{parentName:"p"},"open()")," function.\nThis takes in two argument.\nThe first is a string with name of the file to open.\nThe second is a string indicating what ",(0,i.kt)("em",{parentName:"p"},"mode")," to open the file in."),(0,i.kt)("p",null,"The basic modes (examples will come later):"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},'"r"')," (read mode): Opens the file for reading.\nIf the file does not exist, an error occurs."),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},'"w"')," (write mode): Opens the file for writing.\nIf the file does not exist, it is created.\nIf the file already has content, ",(0,i.kt)("strong",{parentName:"li"},"that content is erased"),' (or "',(0,i.kt)("em",{parentName:"li"},"truncated"),'").'),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},'"a"')," (append mode): Opens the file for writing.\nIf the file does not exist, it is created.\nIf the file already has content, writing occurs ",(0,i.kt)("strong",{parentName:"li"},"after")," the existing content.")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"open()")," will return an object of a special type for files."),(0,i.kt)("p",null,"So, for our example, we want to reverse the lines of ",(0,i.kt)("inlineCode",{parentName:"p"},"words.txt"),"\nand put that in ",(0,i.kt)("inlineCode",{parentName:"p"},"rev_words.txt"),".\nThe former is being read from, and the latter being written to\n(and we aren't updating it/appending to it),\nthat's read and write mode respectively."),(0,i.kt)("p",null,"The code for that so far is (with some extra prints):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'read_file = open("words.txt", "r")\nprint(read_file)\n\nwrite_file = open("rev_words.txt", "w")\nprint(write_file)\n')),(0,i.kt)("p",null,"Doesn't do much yet, although it will make an empty ",(0,i.kt)("inlineCode",{parentName:"p"},'"rev_words.txt"'),".\nFrom those prints, we can see we're definitely getting something new type-wise\nout of ",(0,i.kt)("inlineCode",{parentName:"p"},"open()"),":"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"<_io.TextIOWrapper name='words.txt' mode='r' encoding='UTF-8'>\n<_io.TextIOWrapper name='rev_words.txt' mode='w' encoding='UTF-8'>\n")),(0,i.kt)("h3",{id:"close"},(0,i.kt)("inlineCode",{parentName:"h3"},".close()")),(0,i.kt)("p",null,"Closing files is good practice.\nThe computer has to do a bit of book-keeping for every open file.\nClosing the file frees up the space that was used for the\nbook-keeping associated with that files.\nAt our scale it doesn't really matter, but it's good to adopt the instinct early.\nThis is done with the ",(0,i.kt)("inlineCode",{parentName:"p"},".close()")," method.\nI also recommend closing the file as soon as you can."),(0,i.kt)("p",null,"With proper and early closing of files, the outline of our code becomes:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'read_file = open("words.txt", "r")\n# READ FILE (AND SAVE CONTENTS)\nread_file.close()\n\nwrite_file = open("rev_words.txt", "w")\n# WRITE REVERSED LINES\nwrite_file.close()\n')),(0,i.kt)("h3",{id:"read"},(0,i.kt)("inlineCode",{parentName:"h3"},".read()")),(0,i.kt)("p",null,"Let's actually ",(0,i.kt)("strong",{parentName:"p"},"do")," something now.\nThere are a few different methods for reading from files.\nThe most generic that will work for all files is ",(0,i.kt)("inlineCode",{parentName:"p"},".read()"),".\nThis will just return the whole file as one long string."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'read_file = open("words.txt", "r")\ntext = read_file.read()\nread_file.close()\n\nprint(text) # \'Apple\\nBanana\\nCherry\\nDurian\' \n')),(0,i.kt)("p",null,"Note that in the example I have for ",(0,i.kt)("inlineCode",{parentName:"p"},"words.txt"),", the last line doesn't have a\nnewline after it. I deliberately did that so we would need to worry about/think about\nthe ramifications of that. Often there is a newline after the last line,\nbut that's not a guarantee we have."),(0,i.kt)("p",null,"So what are out other options?\nA common thing we might want to do is split the file into lines\n(which we want to do in our example too).\nOne of the read methods for text files, ",(0,i.kt)("inlineCode",{parentName:"p"},".readlines()"),", returns a list of strings,\none string for each line.\nThe newline characters will still be there, but they can be removed with a comprehension\nand the ",(0,i.kt)("inlineCode",{parentName:"p"}
1,".strip()")," method."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},"read_file = open(\"words.txt\", \"r\")\nlines = read_file.readlines()\nread_file.close()\n\nprint(lines) # ['Apple\\n', 'Banana\\n', 'Cherry\\n', 'Durian']\n\nclean_lines = [line.strip(\"\\n\") for line in lines]\nprint(clean_lines) # ['Apple', 'Banana', 'Cherry', 'Durian']\n")),(0,i.kt)("p",null,"Another option is the ",(0,i.kt)("inlineCode",{parentName:"p"},".readline()")," (singular) method.\nThis reads one line from the file each call,\nand returns it as a string (with the newline character).\nIt returns ",(0,i.kt)("inlineCode",{parentName:"p"},"''")," when it has reached the end of the file."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'read_file = open("words.txt", "r")\n\nwhile True:\n line = read_file.readline()\n if line == "":\n break\n print(line.strip("\\n"))\n\nread_file.close()\n')),(0,i.kt)("p",null,"Finally, forget that, you can straight-up iterate over the file."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'read_file = open("words.txt", "r")\n\nfor line in read_file:\n print(line.strip("\\n"))\n\nread_file.close()\n')),(0,i.kt)("p",null,"That's a lot of options, so what should we use?"),(0,i.kt)("p",null,"If it was a big file and I wanted to process it line-by-line,\nI'd go for for the for-loop approach."),(0,i.kt)("p",null,"If it was a smaller file and I wanted to do something less suited to iteration\n(like reversing the order of lines), I would want one of the bulk-read approaches.\nI find all the the newline stuff annoying and like to get rid of the whole thing.\nFor my money, ",(0,i.kt)("inlineCode",{parentName:"p"},".read()")," combined with the ",(0,i.kt)("inlineCode",{parentName:"p"},".splitlines()")," method\n(turns a string into a list of strings based on newlines)\nfeels like the nicest way to do it."),(0,i.kt)("p",null,"So ",(0,i.kt)("inlineCode",{parentName:"p"},".read().splitlnes()")," it is for reading ",(0,i.kt)("inlineCode",{parentName:"p"},"words.txt"),".\nAs for reversing that list of lines, slicing is overpowered:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},"read_file = open(\"words.txt\", \"r\")\nlines = read_file.read().splitlines()\nread_file.close()\n\nprint(lines) # ['Apple', 'Banana', 'Cherry', 'Durian']\nprint(lines[::-1]) # ['Durian', 'Cherry', 'Banana', 'Apple']\n\nwrite_file = open(\"rev_words.txt\", \"w\")\n# WRITE REVERSED LINES\nwrite_file.close()\n")),(0,i.kt)("h3",{id:"writecontent"},(0,i.kt)("inlineCode",{parentName:"h3"},".write(content)")),(0,i.kt)("p",null,"Finally, writing to a file is done with the ",(0,i.kt)("inlineCode",{parentName:"p"},".write()")," method.\nThis takes in a string to write to the file and writes it."),(0,i.kt)("p",null,"For our reversing lines example, we have the reversed list of lines as strings,\nwe just need to join them together with newlines to get the final string to\nwrite to ",(0,i.kt)("inlineCode",{parentName:"p"},"rev_words.txt"),".\nWell, this is exactly what that weird ",(0,i.kt)("inlineCode",{parentName:"p"},".join()")," string method does."),(0,i.kt)("p",null,"This gives us the solution:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'read_file = open("words.txt", "r")\nlines = read_file.read().splitlines()\nread_file.close()\n\nwrite_file = open("rev_words.txt", "w")\nwrite_file.write("\\n".join(lines[::-1]))\nwrite_file.close()\n')),(0,i.kt)("p",null,"There is also a ",(0,i.kt)("inlineCode",{parentName:"p"},".writelines()")," method for text files.\nThis takes in an iterable of strings and writes each to the file.\nNote: it does not add newlines to these string,\nthey must have newlines at the end already."),(0,i.kt)("p",null,"So if we were guaranteed that the last line of the file had a newline at the end of it,\nand we wanted the last line of ",(0,i.kt)("inlineCode",{parentName:"p"},"rev_words.txt")," to have a newline it the end of it,\nthis would be a very elegant solution:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'read_file = open("words.txt", "r")\nlines = read_file.readlines()\nread_file.close()\n\nwrite_file = open("rev_words.txt", "w")\nwrite_file.writelines(lines[::-1])\nwrite_file.close()\n')),(0,i.kt)("h3",{id:"write-vs-append"},"Write vs. Append"),(0,i.kt)("p",null,"I promised some examples on opening in write mode vs append mode.\nWrite mode and append mode function the same on empty files (they make a new one).\nSo it suffices to restrict our consideration to when a file already exists."),(0,i.kt)("p",null,"When writing to a file that already exists, the old content is truncated."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'# File is made\nwrite_file = open("more_words.txt", "w")\nwrite_file.write("Long ago,\\n")\nwrite_file.write("In a distant land,\\n")\nwrite_file.write("I ... \\n")\nwrite_file.close()\n\n# File is over-written\nover_write_file = open("more_words.txt", "w")\nwrite_file.write("Back to the past.")\nwrite_file.close()\n')),(0,i.kt)("p",null,"When the above code is run, the final content of ",(0,i.kt)("inlineCode",{parentName:"p"},"more_text.txt")," will be:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"Back to the past.\n")),(0,i.kt)("p",null,"Because, opening up ",(0,i.kt)("inlineCode",{parentName:"p"},"more_text.txt")," in write mode erases\nall the stuff that was originally written to it."),(0,i.kt)("p",null,"When appending to a file that already exists, the old content is left alone,\nwith new content being added afterwards."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'# File is made\nwrite_file = open("more_words.txt", "w")\nwrite_file.write("Long ago,\\n")\nwrite_file.write("In a distant land,\\n")\nwrite_file.write("I ... \\n")\nwrite_file.close()\n\n# File is appended to\nappend_file = open("more_words.txt", "a")\nappend_file.write("unleashed an unspeakable evil.")\nappend_file.close()\n')),(0,i.kt)("p",null,"When the above code is run, the final content of ",(0,i.kt)("inlineCode",{parentName:"p"},"more_text.txt")," will be:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"Long ago,\nIn a distant land,\nI ... \nunleashed an unspeakable evil.\n")),(0,i.kt)("p",null,"Because, opening up ",(0,i.kt)("inlineCode",{parentName:"p"},"more_text.txt")," in append mode\nadds new stuff to the existing stuff."),(0,i.kt)("h3",{id:"with-and-as"},(0,i.kt)("inlineCode",{parentName:"h3"},"with")," and ",(0,i.kt)("inlineCode",{parentName:"h3"},"as")),(0,i.kt)("p",null,"The worrying about closing files business is a tad annoying.\nWorse, if some weird error occur while processing the file,\nthen we may not be able to properly close it\n(rather, we'd need try-excepts and error handling to make sure it closes)."),(0,i.kt)("p",null,"There is special syntax that lets us open a file in a way that will automatically close it,\neven with error shenanigans:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},"with open(arguements...) as file_var_name:\n code_block\n")),(0,i.kt)("p",null,"We have:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"The keyword ",(0,i.kt)("inlineCode",{parentName:"li"},"with")),(0,i.kt)("li",{parentName:"ul"},"The ",(0,i.kt)("inlineCode",{parentName:"li"},"open()")," call for how we want to open the file"),(0,i.kt)("li",{parentName:"ul"},"The keyword ",(0,i.kt)("inlineCode",{parentName:"li"},"as")),(0,i.kt)("li",{parentName:"ul"},"The variable name ",(0,i.kt)("inlineCode",{parentName:"li"},"file_var_name"),", to which the opened file will be assigned"),(0,i.kt)("li",{parentName:"ul"},"The colon (",(0,i.kt)("inlineCode",{parentName:"li"},":"),")"),(0,i.kt)("li",{parentName:"ul"},"The code block (",(0,i.kt)("inlineCode",{parentName:"li"},"code_block"),"), which may make use of the variable ",(0,i.kt)("inlineCode",{parentName:"li"},"file_var_name"))),(0,i.kt)("p",null,"I think you can probably guess what this does, but: It opens the file, assigns it to\n",(0,i.kt)("inlineCode",{parentName:"p"},"file_var_name"),", runs ",(0,i.kt)("inlineCode",{parentName:"p"},"code_block"),", and closes the file at the end (or if an error occurs)."),(0,i.kt)("p",null,"With this, our earlier reverse-file-lines solution can be refactored like so:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'with open("words.txt", "r") as read_file:\n lines = read_file.read().splitlines()\n\nwith open("rev_words.txt", "w") as write_file:\n write_file.write("\\n".join(l
1ines[::-1]))\n')),(0,i.kt)("h2",{id:"files-in-other-places"},"Files in Other Places"),(0,i.kt)("p",null,"All of this has been based on the idea that the file being opened is in\nthe same folder as the code we are running. This won't always be the case."),(0,i.kt)("h3",{id:"directory-hierarchy"},"Directory Hierarchy"),(0,i.kt)("p",null,"We need a brief interlude about the ",(0,i.kt)("em",{parentName:"p"},"file system"),' on computers,\nhow the system is structured/"where files are"\n(in the model at any rate; where they actually are is a much more complicated story).'),(0,i.kt)("p",null,"Your computer has ",(0,i.kt)("em",{parentName:"p"},"folders")," (also called ",(0,i.kt)("em",{parentName:"p"},"directories"),") and ",(0,i.kt)("em",{parentName:"p"},"files"),".\nThere is a top-level/root folder somewhere,\nbut you won't need to worry about that one beyond the fact that it exists.\nWithin each folder there may a combination of files and more folders."),(0,i.kt)("p",null,"In particular, there is some folder that your python script is in, and (for our purposes)\nthat will serve as the starting location that your code looks for files in."),(0,i.kt)("p",null,"So here an example of some files somewhere in a file system (explained below):"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"CICS 110\n|-- about.txt\n|-- notes\n| |-- lecture_01.txt\n|-- sandbox <-- ** HERE **\n |-- files\n | |-- bar\n | | |-- baz.txt\n | |-- foo.txt\n |-- main.py\n |-- words.txt\n")),(0,i.kt)("p",null,"What does all this mean:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},"There is a ",(0,i.kt)("inlineCode",{parentName:"li"},"CICS 110")," folder."),(0,i.kt)("li",{parentName:"ul"},"Within that ",(0,i.kt)("inlineCode",{parentName:"li"},"CICS 110")," folder is the file ",(0,i.kt)("inlineCode",{parentName:"li"},"about.txt")," and the folders ",(0,i.kt)("inlineCode",{parentName:"li"},"notes")," and ",(0,i.kt)("inlineCode",{parentName:"li"},"sandbox"),"."),(0,i.kt)("li",{parentName:"ul"},"Within that ",(0,i.kt)("inlineCode",{parentName:"li"},"notes")," folder is the file ",(0,i.kt)("inlineCode",{parentName:"li"},"lecture_01.txt"),"."),(0,i.kt)("li",{parentName:"ul"},"That ",(0,i.kt)("inlineCode",{parentName:"li"},"sandbox")," folder is the open project in VSCode, for the purposes of this example."),(0,i.kt)("li",{parentName:"ul"},"Within that ",(0,i.kt)("inlineCode",{parentName:"li"},"sandbox")," folder are the files ",(0,i.kt)("inlineCode",{parentName:"li"},"main.py")," (our script) and ",(0,i.kt)("inlineCode",{parentName:"li"},"words.txt")," and\nthe folder ",(0,i.kt)("inlineCode",{parentName:"li"},"files"),"."),(0,i.kt)("li",{parentName:"ul"},"Within that ",(0,i.kt)("inlineCode",{parentName:"li"},"files")," folder is the file ",(0,i.kt)("inlineCode",{parentName:"li"},"foo.txt")," and the folder ",(0,i.kt)("inlineCode",{parentName:"li"},"bar"),"."),(0,i.kt)("li",{parentName:"ul"},"Within that ",(0,i.kt)("inlineCode",{parentName:"li"},"bar")," folder is the file ",(0,i.kt)("inlineCode",{parentName:"li"},"baz.txt"),".")),(0,i.kt)("p",null,"So if we wanted ",(0,i.kt)("inlineCode",{parentName:"p"},"main.py")," to just read and print the contents of the file ",(0,i.kt)("inlineCode",{parentName:"p"},"words.txt"),",\nwe just do that as before:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'with open("words.txt", "r") as read_file:\n contents = read_file.read()\n print(contents)\n')),(0,i.kt)("h3",{id:"children"},"Children"),(0,i.kt)("p",null,"Running example for reference:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"CICS 110\n|-- about.txt\n|-- notes\n| |-- lecture_01.txt\n|-- sandbox <-- ** HERE **\n |-- files\n | |-- bar\n | | |-- baz.txt\n | |-- foo.txt\n |-- main.py\n |-- words.txt\n")),(0,i.kt)("p",null,"What if we wanted ",(0,i.kt)("inlineCode",{parentName:"p"},"main.py")," to open ",(0,i.kt)("inlineCode",{parentName:"p"},"foo.txt"),"?\nWe might try this:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'with open("foo.txt", "r") as read_file: # ERROR\n contents = read_file.read()\n print(contents)\n')),(0,i.kt)("p",null,"This throws an error indicating the file doesn't exist.\n",(0,i.kt)("inlineCode",{parentName:"p"},"main.py")," is going to look for a file named ",(0,i.kt)("inlineCode",{parentName:"p"},"foo.txt")," in\nit's current directory (",(0,i.kt)("inlineCode",{parentName:"p"},"sandbox"),"), which indeed does not have a ",(0,i.kt)("inlineCode",{parentName:"p"},"foo.txt")," file."),(0,i.kt)("p",null,'We need to say "go to the ',(0,i.kt)("inlineCode",{parentName:"p"},"files")," folder, and get the file ",(0,i.kt)("inlineCode",{parentName:"p"},"foo.txt"),'".\nWe write that as ',(0,i.kt)("inlineCode",{parentName:"p"},"files/foo.txt"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'with open("files/foo.txt", "r") as read_file:\n contents = read_file.read()\n print(contents)\n')),(0,i.kt)("p",null,'And these slashes can be chained. So for instance,\n"go to ',(0,i.kt)("inlineCode",{parentName:"p"},"files"),", go to ",(0,i.kt)("inlineCode",{parentName:"p"},"bar"),", get ",(0,i.kt)("inlineCode",{parentName:"p"},"baz.txt"),'" is ',(0,i.kt)("inlineCode",{parentName:"p"},"files/bar/baz.txt"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'with open("files/bar/baz.txt", "r") as read_file:\n contents = read_file.read()\n print(contents)\n')),(0,i.kt)("h3",{id:"parent"},"Parent"),(0,i.kt)("p",null,"Running example for reference:"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre"},"CICS 110\n|-- about.txt\n|-- notes\n| |-- lecture_01.txt\n|-- sandbox <-- ** HERE **\n |-- files\n | |-- bar\n | | |-- baz.txt\n | |-- foo.txt\n |-- main.py\n |-- words.txt\n")),(0,i.kt)("p",null,'So we can go down, but what about up? What if we wanted to\nsay "go to ',(0,i.kt)("inlineCode",{parentName:"p"},"CICS 110"),", get ",(0,i.kt)("inlineCode",{parentName:"p"},"about.txt"),'". Well, since ',(0,i.kt)("inlineCode",{parentName:"p"},"CICS 110")," isn't in\n",(0,i.kt)("inlineCode",{parentName:"p"},"sandbox")," we can't quite do that.\nBut we can say \"go ",(0,i.kt)("strong",{parentName:"p"},"up"),", get ",(0,i.kt)("inlineCode",{parentName:"p"},"about.txt"),'".\nWe write that as ',(0,i.kt)("inlineCode",{parentName:"p"},"../about.txt"),",\nwhere the ",(0,i.kt)("inlineCode",{parentName:"p"},"..")," is a special reference for the parent directory."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'with open("../about.txt", "r") as read_file:\n contents = read_file.read()\n print(contents)\n')),(0,i.kt)("p",null,"Make sure to use ",(0,i.kt)("inlineCode",{parentName:"p"}
1,"../about.txt"),", and not ",(0,i.kt)("inlineCode",{parentName:"p"},"./about.txt"),".\nThe single dot is a special reference to the current directory\n(so ",(0,i.kt)("inlineCode",{parentName:"p"},"./words.txt")," would be the same file as ",(0,i.kt)("inlineCode",{parentName:"p"},"words.txt"),")."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'with open("./words.txt", "r") as read_file:\n contents = read_file.read()\n print(contents)\n')),(0,i.kt)("p",null,'And again, chaining is possible. "go up, go to ',(0,i.kt)("inlineCode",{parentName:"p"},"notes"),", get ",(0,i.kt)("inlineCode",{parentName:"p"},"lecture_01.txt"),'"\nwould be ',(0,i.kt)("inlineCode",{parentName:"p"},"../notes/lecture_01.txt"),"."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-py"},'with open("../notes/lecture_01.txt", "r") as read_file:\n contents = read_file.read()\n print(contents)\n')))}h.isMDXComponent=!0}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.