108 lines
No EOL
16 KiB
HTML
108 lines
No EOL
16 KiB
HTML
<!DOCTYPE html><html><head><meta content="text/html; charset=utf-8" http-equiv="Content-Type" /><meta content="width=device-width, initial-scale=1" name="viewport" /><!--replace-start-0--><!--replace-start-5--><!--replace-start-8--><title>IO in Python - My Zettelkasten</title><!--replace-end-8--><!--replace-end-5--><!--replace-end-0--><link href="https://cdn.jsdelivr.net/npm/fomantic-ui@2.8.7/dist/semantic.min.css" rel="stylesheet" /><link href="https://fonts.googleapis.com/css?family=Merriweather|Libre+Franklin|Roboto+Mono&display=swap" rel="stylesheet" /><!--replace-start-1--><!--replace-start-4--><!--replace-start-7--><link href="https://raw.githubusercontent.com/srid/neuron/master/assets/neuron.svg" rel="icon" /><meta content="The built-in open() function creates a file object that allows us to read, write and append to files." name="description" /><meta content="IO in Python" property="og:title" /><meta content="My Zettelkasten" property="og:site_name" /><meta content="article" property="og:type" /><meta content="IO_in_Python" property="neuron:zettel-id" /><meta content="IO_in_Python" property="neuron:zettel-slug" /><meta content="python" property="neuron:zettel-tag" /><script type="application/ld+json">[]</script><style type="text/css">body{background-color:#eeeeee !important;font-family:"Libre Franklin", serif !important}body .ui.container{font-family:"Libre Franklin", serif !important}body h1, h2, h3, h4, h5, h6, .ui.header, .headerFont{font-family:"Merriweather", sans-serif !important}body code, pre, tt, .monoFont{font-family:"Roboto Mono","SFMono-Regular","Menlo","Monaco","Consolas","Liberation Mono","Courier New", monospace !important}body div.z-index p.info{color:#808080}body div.z-index ul{list-style-type:square;padding-left:1.5em}body div.z-index .uplinks{margin-left:0.29999em}body .zettel-content h1#title-h1{background-color:rgba(33,133,208,0.1)}body nav.bottomPane{background-color:rgba(33,133,208,2.0e-2)}body div#footnotes{border-top-color:#2185d0}body p{line-height:150%}body img{max-width:100%}body .deemphasized{font-size:0.94999em}body .deemphasized:hover{opacity:1}body .deemphasized:not(:hover){opacity:0.69999}body .deemphasized:not(:hover) a{color:#808080 !important}body div.container.universe{padding-top:1em}body div.zettel-view ul{padding-left:1.5em;list-style-type:square}body div.zettel-view .pandoc .highlight{background-color:#ffff00}body div.zettel-view .pandoc .ui.disabled.fitted.checkbox{margin-right:0.29999em;vertical-align:middle}body div.zettel-view .zettel-content .metadata{margin-top:1em}body div.zettel-view .zettel-content .metadata div.date{text-align:center;color:#808080}body div.zettel-view .zettel-content h1{padding-top:0.2em;padding-bottom:0.2em;text-align:center}body div.zettel-view .zettel-content h2{border-bottom:solid 1px #4682b4;margin-bottom:0.5em}body div.zettel-view .zettel-content h3{margin:0px 0px 0.4em 0px}body div.zettel-view .zettel-content h4{opacity:0.8}body div.zettel-view .zettel-content div#footnotes{margin-top:4em;border-top-style:groove;border-top-width:2px;font-size:0.9em}body div.zettel-view .zettel-content div#footnotes ol > li > p:only-of-type{display:inline;margin-right:0.5em}body div.zettel-view .zettel-content aside.footnote-inline{width:30%;padding-left:15px;margin-left:15px;float:right;background-color:#d3d3d3}body div.zettel-view .zettel-content .overflows{overflow:auto}body div.zettel-view .zettel-content code{margin:auto auto auto auto;font-size:100%}body div.zettel-view .zettel-content p code, li code, ol code{padding:0.2em 0.2em 0.2em 0.2em;background-color:#f5f2f0}body div.zettel-view .zettel-content pre{overflow:auto}body div.zettel-view .zettel-content dl dt{font-weight:bold}body div.zettel-view .zettel-content blockquote{background-color:#f9f9f9;border-left:solid 10px #cccccc;margin:1.5em 0px 1.5em 0px;padding:0.5em 10px 0.5em 10px}body div.zettel-view .zettel-content.raw{background-color:#dddddd}body .ui.label.zettel-tag{color:#000000}body .ui.label.zettel-tag a{color:#000000}body nav.bottomPane ul.backlinks > li{padding-bottom:0.4em;list-style-type:disc}body nav.bottomPane ul.context-list > li{list-style-type:lower-roman}body .footer-version img{-webkit-filter:grayscale(100%);-moz-filter:grayscale(100%);-ms-filter:grayscale(100%);-o-filter:grayscale(100%);filter:grayscale(100%)}body .footer-version img:hover{-webkit-filter:grayscale(0%);-moz-filter:grayscale(0%);-ms-filter:grayscale(0%);-o-filter:grayscale(0%);filter:grayscale(0%)}body .footer-version, .footer-version a, .footer-version a:visited{color:#808080}body .footer-version a{font-weight:bold}body .footer-version{margin-top:1em !important;font-size:0.69999em}@media only screen and (max-width: 768px){body div#zettel-container{margin-left:0.4em !important;margin-right:0.4em !important}}body span.zettel-link-container span.zettel-link a{color:#2185d0;font-weight:bold;text-decoration:none}body span.zettel-link-container span.zettel-link a:hover{background-color:rgba(33,133,208,0.1)}body span.zettel-link-container span.extra{color:auto}body span.zettel-link-container.errors{border:solid 1px #ff0000}body span.zettel-link-container.errors span.zettel-link a:hover{text-decoration:none !important;cursor:not-allowed}body [data-tooltip]:after{font-size:0.69999em}body div.tag-tree div.node{font-weight:bold}body div.tag-tree div.node a.inactive{color:#555555}body .tree.flipped{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}body .tree{overflow:auto}body .tree ul.root{padding-top:0px;margin-top:0px}body .tree ul{position:relative;padding:1em 0px 0px 0px;white-space:nowrap;margin:0px auto 0px auto;text-align:center}body .tree ul::after{content:"";display:table;clear:both}body .tree ul:last-child{padding-bottom:0.1em}body .tree li{display:inline-block;vertical-align:top;text-align:center;list-style-type:none;position:relative;padding:1em 0.5em 0em 0.5em}body .tree li::before{content:"";position:absolute;top:0px;right:50%;border-top:solid 2px #cccccc;width:50%;height:1.19999em}body .tree li::after{content:"";position:absolute;top:0px;right:50%;border-top:solid 2px #cccccc;width:50%;height:1.19999em}body .tree li::after{right:auto;left:50%;border-left:solid 2px #cccccc}body .tree li:only-child{padding-top:0em}body .tree li:only-child::after{display:none}body .tree li:only-child::before{display:none}body .tree li:first-child::before{border-style:none;border-width:0px}body .tree li:first-child::after{border-radius:5px 0px 0px 0px}body .tree li:last-child::after{border-style:none;border-width:0px}body .tree li:last-child::before{border-right:solid 2px #cccccc;border-radius:0px 5px 0px 0px}body .tree ul ul::before{content:"";position:absolute;top:0px;left:50%;border-left:solid 2px #cccccc;width:0px;height:1.19999em}body .tree li div.forest-link{border:solid 2px #cccccc;padding:0.2em 0.29999em 0.2em 0.29999em;text-decoration:none;display:inline-block;border-radius:5px 5px 5px 5px;color:#333333;position:relative;top:2px}body .tree.flipped li div.forest-link{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}</style><script
|
|
async=""
|
|
id="MathJax-script"
|
|
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"
|
|
></script>
|
|
<link
|
|
href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/themes/prism.min.css"
|
|
rel="stylesheet"
|
|
/><link rel="preconnect" href="https://fonts.googleapis.com" /><link
|
|
rel="preconnect"
|
|
href="https://fonts.gstatic.com"
|
|
crossorigin
|
|
/><link
|
|
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&family=IBM+Plex+Sans+Condensed:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&family=IBM+Plex+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&family=IBM+Plex+Serif:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap"
|
|
rel="stylesheet"
|
|
/>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/components/prism-core.min.js"></script>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/plugins/autoloader/prism-autoloader.min.js"></script>
|
|
<style>
|
|
body .ui.container,
|
|
body ul {
|
|
font-family: "IBM Plex Sans" !important;
|
|
}
|
|
body blockquote {
|
|
border-left-width: 3px !important;
|
|
font-style: italic;
|
|
}
|
|
.headerFont,
|
|
.ui.header,
|
|
body h1,
|
|
h2,
|
|
h3,
|
|
h4,
|
|
h5,
|
|
h6 {
|
|
font-family: "IBM Plex Sans Condensed" !important;
|
|
}
|
|
body p {
|
|
line-height: 1.4;
|
|
}
|
|
.monoFont,
|
|
body code,
|
|
pre,
|
|
tt {
|
|
font-family: "IBM Plex Mono" !important;
|
|
font-size: 12px !important;
|
|
line-height: 1.4 !important;
|
|
}
|
|
</style>
|
|
<!--replace-end-7--><!--replace-end-4--><!--replace-end-1--></head><body><div class="ui fluid container universe"><!--replace-start-2--><!--replace-start-3--><!--replace-start-6--><div class="ui text container" id="zettel-container" style="position: relative"><div class="zettel-view"><article class="ui raised attached segment zettel-content"><div class="pandoc"><h1 id="title-h1">IO in Python</h1><h2 id="the-open-object">The open() object</h2><p>The built-in <code>open()</code> function creates a <strong>file object</strong> that allows us to read, write and append to files.</p><p>The general syntax is as follows:</p><pre><code class="py language-py">file_object = open(<file_name>, <access_mode>)</code></pre><p><code><file_name></code> is obviously a path to the file you want to read, create or modify. The <code><access_mode></code> denotes the mode in which to open the file. The most frequently used are:</p><ul><li><code>r</code><ul><li>read</li></ul></li><li><code>w</code><ul><li>write</li></ul></li><li><code>a</code><ul><li>append</li></ul></li></ul><h3 id="all-access-modes">All access modes</h3><p>In addition we have the following access modes</p><h2 id="reading-files">Reading files</h2><p>Once a file object has been intialised with <code>open()</code> there are several ways in which the content can be read:</p><table class="ui table"><thead><tr><th>Read method</th><th>Behaviour</th></tr></thead><tbody><tr><td><code>read</code></td><td>Return the entire contents of the file as a single string.</td></tr><tr><td><code>readline</code></td><td>Read the contents of a file a line at a time. You would combine this with a loop so that you can do something with each individual line.</td></tr><tr><td><code>readlines</code></td><td>Return a list of all the lines in a file. Each line will be an element in the list.</td></tr></tbody></table><h3 id="read">Read</h3><p><code>read</code> reads the entire contents of a file and returns it as a single string.</p><p><code>read()</code> reads the entire file into memory at once, so it may not be suitable for very large files that exceed the available memory of your system. In such cases, you can use the <code>readline()</code> method to read the file line by line instead.</p><p>The basic syntax is as follows:</p><pre><code class="py language-py"># Open the file for reading
|
|
file = open('filename.txt', 'r')
|
|
|
|
# Read the entire contents of the file
|
|
contents = file.read()
|
|
|
|
# We could also limit the read to a number of characters:
|
|
contents = file.read(100)
|
|
|
|
# Close the file
|
|
file.close()</code></pre><p>Once we have the file contents stored, we can then interact with it. The standard way of doing this is to parse it line by line. For example, say we were reading a CSV:</p><pre><code class="py language-py">lines = content.split(',')
|
|
for line in lines:
|
|
if line: # if the line is not empty
|
|
# do something with line</code></pre><h3 id="readline">Readline</h3><blockquote><p>The readline() method in Python is used to read a single line from a file. It is typically used when you want to process a file line by line, rather than reading the entire file into memory at once.</p></blockquote><p><code>readline()</code> returns the line including the newline character at the end of the line, so you may need to strip this character off using the strip() method before processing the line further.</p><pre><code class="python language-python"># Open the file for reading
|
|
file = open('filename.txt', 'r')
|
|
|
|
# Loop through the file, reading one line at a time
|
|
line = file.readline()
|
|
while line:
|
|
# Strip off the newline character
|
|
line = line.strip()
|
|
|
|
# Do something with the line
|
|
print(line)
|
|
|
|
# Read the next line
|
|
line = file.readline()
|
|
|
|
# Close the file
|
|
file.close()</code></pre><h3 id="readlines">Readlines</h3><p>The <code>readlines()</code> method is used to read all the lines of a file and return them as a list of strings, where each element of the list is a line from the file.</p><pre><code class="py language-py"># Open the file for reading
|
|
file = open('filename.txt', 'r')
|
|
|
|
# Read all the lines of the file and store them in a list
|
|
lines = file.readlines()
|
|
|
|
# Loop through the lines and print them to the console
|
|
for line in lines:
|
|
print(line)
|
|
|
|
# Close the file
|
|
file.close()</code></pre><h3 id="error-handling">Error handling</h3><p>Obviously file access can raise errors - typically when the file you want to access does not exist (i.e. a <code>FileNotFoundError</code> <span class="zettel-link-container cf"><span class="zettel-link" title="Zettel: Error handling and exceptions in Python"><a href="Error_handling_in_Python.html">exception</a></span></span>). We can manage this scenario with <span class="zettel-link-container cf"><span class="zettel-link" title="Zettel: Error handling and exceptions in Python"><a href="Error_handling_in_Python.html">exception handlers</a></span></span>:</p><pre><code class="py language-py">try:
|
|
with open('filename.txt', 'r') as file:
|
|
contents = file.readlines()
|
|
for line in lines:
|
|
print(line)
|
|
except FileNotFoundError as err:
|
|
print("File does not exist")
|
|
print(err)</code></pre><h2 id="close-and-with-as">Close and “with as”</h2><p>You notice that once we have finished with our I/O operation, we must call <code>file.close()</code> to terminate the process. This removes the reference to the file from memory.</p><p>A more pythonic and concise way of reading files and closing them is to use <code>with...as</code> syntax. When this phrasing is used, a self-contained context is created for the I/O operation that closes the file automatically.</p><pre><code class="py language-py">with open('filename.txt', 'r') as file:
|
|
contents = file.read()
|
|
print(contents)</code></pre><h2 id="writing-to-files">Writing to files</h2><p>Again we create a file object with <code>open()</code> and this time use the <code>write</code> method:</p><pre><code class="py language-py"># Open file in write mode
|
|
file = open("example.txt", "w")
|
|
|
|
# Write some text to the file
|
|
file.write("Hello, this is an example text written using Python.")
|
|
|
|
# Close the file
|
|
file.close()</code></pre><blockquote><p>Note that in the above example, if the file does not already exist, it will create it. If it does exist, it will overwrite its contents with the new data. So we use <code>write</code> to create new files as well as to write to existing files.</p></blockquote><h2 id="renaming-and-deleting-files">Renaming and deleting files</h2><p>We have to use another built-in module to rename and delete files: <code>os</code>.</p><p>To rename an existing file:</p><pre><code class="py language-py">import os
|
|
os.rename('original-file-name.txt', 'new-file-name.txt')</code></pre><p>To delete a file:</p><pre><code class="py language-py">import os
|
|
os.remove('file-name.txt')</code></pre></div></article><nav class="ui attached segment deemphasized bottomPane" id="neuron-tags-pane"><div><span class="ui basic label zettel-tag" title="Tag">python</span></div></nav><nav class="ui bottom attached icon compact inverted menu blue" id="neuron-nav-bar"><!--replace-start-9--><!--replace-end-9--><a class="right item" href="impulse.html" title="Open Impulse"><i class="wave square icon"></i></a></nav></div></div><!--replace-end-6--><!--replace-end-3--><!--replace-end-2--><div class="ui center aligned container footer-version"><div class="ui tiny image"><a href="https://neuron.zettel.page"><img alt="logo" src="https://raw.githubusercontent.com/srid/neuron/master/assets/neuron.svg" title="Generated by Neuron 1.9.35.3" /></a></div></div></div></body></html> |