10-21-2022, 09:47 AM
How to Return a File From a Function in Python?
<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"810478","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<p>Do you need to <strong>create a function that returns a file </strong>but you don’t know how? No worries, in sixty seconds, you’ll know! Go! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p class="has-pale-cyan-blue-background-color has-background">A Python function can return any object such as a file object. To return a file, first open the file object within the function body, handle all possible errors if the file doesn’t exist, and return it to the caller of the function using the <a title="Return Keyword in Python – A Simple Illustrated Guide" rel="noreferrer noopener" href="https://blog.finxter.com/python-return/" target="_blank">keyword </a>operation <code>return open(filename, mode='r')</code>. </p>
<p>Here’s a minimal example that tries to open a filename that was provided by the user via the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-input-function/" data-type="post" data-id="24632" target="_blank">input()</a></code> function. If it fails, it <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">prints</a> an error message and asks for a different user input:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def open_file(): while True: filename = input('filename: ') try: return open(filename, mode='r') except: print('Error. Try again') f = open_file()
print(f.read()) </pre>
<p>If I type in the correct file right away, I get the following output when storing the previous code snippet in a file named <code>code.py</code>—the code reads itself (meta <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f92f.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">filename: code.py
def open_file(): while True: filename = input('filename: ') try: return open(filename, mode='r') except: print('Error. Try again') f = open_file()
print(f.read())</pre>
<p>Note that you can open the file in <strong><em>writing mode</em></strong> rather than reading mode by replacing the line with the <code>return</code> statement with the following line:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">open(filename, mode='w')</pre>
<p>A more Pythonic way, in my opinion, is to follow the <a rel="noreferrer noopener" href="https://blog.finxter.com/tips-to-write-clean-code/" data-type="post" data-id="17059" target="_blank">single-responsibility pattern</a> whereby a function should do only one thing. In that case, provide the relevant input values into the function like so:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def open_file(filename, mode): try: return open(filename, mode=mode) except: return None def ask_user(): f = open_file(input('filename: '), input('mode: ')) while not f: f = open_file(input('filename: '), input('mode: ')) return f f = ask_user() print(f.read()) </pre>
<p>Notice how the file handling of a single instance and the user input processing are separated into two functions. Each function does one thing only. <a href="https://blog.finxter.com/the-unix-philosophy/" data-type="post" data-id="19704" target="_blank" rel="noreferrer noopener">Unix style.</a></p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<p>If you want to improve your programming skills and coding productivity creating massive success with your apps and coding projects, feel free to check out my book on the topic:</p>
<hr class="wp-block-separator"/>
<h2>The Art of Clean Code</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank" rel="noopener"><img loading="lazy" width="325" height="427" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-269.png" alt="" class="wp-image-385474" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-269.png 325w, https://blog.finxter.com/wp-content/uplo...28x300.png 228w" sizes="(max-width: 325px) 100vw, 325px" /></a></figure>
</div>
<p>Most software developers waste thousands of hours working with overly complex code. The eight core principles in The Art of Clean Coding will teach you how to write clear, maintainable code without compromising functionality. The book’s guiding principle is simplicity: reduce and simplify, then reinvest energy in the important parts to save you countless hours and ease the often onerous task of code maintenance.</p>
<ol>
<li>Concentrate on the important stuff with the <strong>80/20 principle</strong> — focus on the 20% of your code that matters most</li>
<li>Avoid coding in isolation: create a <strong>minimum viable product</strong> to get early feedback</li>
<li>Write code cleanly and simply to <strong>eliminate clutter</strong> </li>
<li><strong>Avoid premature optimization</strong> that risks over-complicating code </li>
<li>Balance your goals, capacity, and feedback to achieve the productive state of <strong>Flow</strong></li>
<li>Apply the <strong>Do One Thing Well</strong> philosophy to vastly improve functionality</li>
<li>Design efficient user interfaces with the <strong>Less is More</strong> principle</li>
<li>Tie your new skills together into one unifying principle: <strong>Focus</strong></li>
</ol>
<p>The Python-based <em><strong><a rel="noreferrer noopener" href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" data-type="URL" data-id="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank">The Art of Clean Coding</a></strong></em> is suitable for programmers at any level, with ideas presented in a language-agnostic manner.</p>
<div class="wp-container-1 is-content-justification-center wp-block-buttons">
<div class="wp-block-button has-custom-width wp-block-button__width-50"><a class="wp-block-button__link" href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank" rel="noreferrer noopener">Get My Book on Amazon!</a></div>
</div>
<hr class="wp-block-separator"/>
<h2>Related Tutorials</h2>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-return-string-from-function/" data-type="post" data-id="784920" target="_blank">Python Return String From Function</a></li>
<li><a href="https://blog.finxter.com/python-return-dictionary-from-function/" data-type="post" data-id="34362" target="_blank" rel="noreferrer noopener">Python Return Dict From Function</a></li>
<li><a href="https://blog.finxter.com/python-return-set-from-function/" data-type="post" data-id="34346" target="_blank" rel="noreferrer noopener">Python Return Set From Function</a></li>
</ul>
<h2>Programmer Humor</h2>
<pre class="wp-block-preformatted has-global-color-8-background-color has-background"><code><strong>Q</strong>: How do you tell an introverted computer scientist from an extroverted computer scientist? <strong>A</strong>: An extroverted computer scientist looks at <strong><em>your</em></strong> shoes when he talks to you.</code></pre>
</div>
https://www.sickgaming.net/blog/2022/10/...in-python/
<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"810478","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<p>Do you need to <strong>create a function that returns a file </strong>but you don’t know how? No worries, in sixty seconds, you’ll know! Go! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p class="has-pale-cyan-blue-background-color has-background">A Python function can return any object such as a file object. To return a file, first open the file object within the function body, handle all possible errors if the file doesn’t exist, and return it to the caller of the function using the <a title="Return Keyword in Python – A Simple Illustrated Guide" rel="noreferrer noopener" href="https://blog.finxter.com/python-return/" target="_blank">keyword </a>operation <code>return open(filename, mode='r')</code>. </p>
<p>Here’s a minimal example that tries to open a filename that was provided by the user via the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-input-function/" data-type="post" data-id="24632" target="_blank">input()</a></code> function. If it fails, it <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">prints</a> an error message and asks for a different user input:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def open_file(): while True: filename = input('filename: ') try: return open(filename, mode='r') except: print('Error. Try again') f = open_file()
print(f.read()) </pre>
<p>If I type in the correct file right away, I get the following output when storing the previous code snippet in a file named <code>code.py</code>—the code reads itself (meta <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f92f.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">filename: code.py
def open_file(): while True: filename = input('filename: ') try: return open(filename, mode='r') except: print('Error. Try again') f = open_file()
print(f.read())</pre>
<p>Note that you can open the file in <strong><em>writing mode</em></strong> rather than reading mode by replacing the line with the <code>return</code> statement with the following line:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">open(filename, mode='w')</pre>
<p>A more Pythonic way, in my opinion, is to follow the <a rel="noreferrer noopener" href="https://blog.finxter.com/tips-to-write-clean-code/" data-type="post" data-id="17059" target="_blank">single-responsibility pattern</a> whereby a function should do only one thing. In that case, provide the relevant input values into the function like so:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def open_file(filename, mode): try: return open(filename, mode=mode) except: return None def ask_user(): f = open_file(input('filename: '), input('mode: ')) while not f: f = open_file(input('filename: '), input('mode: ')) return f f = ask_user() print(f.read()) </pre>
<p>Notice how the file handling of a single instance and the user input processing are separated into two functions. Each function does one thing only. <a href="https://blog.finxter.com/the-unix-philosophy/" data-type="post" data-id="19704" target="_blank" rel="noreferrer noopener">Unix style.</a></p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<p>If you want to improve your programming skills and coding productivity creating massive success with your apps and coding projects, feel free to check out my book on the topic:</p>
<hr class="wp-block-separator"/>
<h2>The Art of Clean Code</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank" rel="noopener"><img loading="lazy" width="325" height="427" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-269.png" alt="" class="wp-image-385474" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-269.png 325w, https://blog.finxter.com/wp-content/uplo...28x300.png 228w" sizes="(max-width: 325px) 100vw, 325px" /></a></figure>
</div>
<p>Most software developers waste thousands of hours working with overly complex code. The eight core principles in The Art of Clean Coding will teach you how to write clear, maintainable code without compromising functionality. The book’s guiding principle is simplicity: reduce and simplify, then reinvest energy in the important parts to save you countless hours and ease the often onerous task of code maintenance.</p>
<ol>
<li>Concentrate on the important stuff with the <strong>80/20 principle</strong> — focus on the 20% of your code that matters most</li>
<li>Avoid coding in isolation: create a <strong>minimum viable product</strong> to get early feedback</li>
<li>Write code cleanly and simply to <strong>eliminate clutter</strong> </li>
<li><strong>Avoid premature optimization</strong> that risks over-complicating code </li>
<li>Balance your goals, capacity, and feedback to achieve the productive state of <strong>Flow</strong></li>
<li>Apply the <strong>Do One Thing Well</strong> philosophy to vastly improve functionality</li>
<li>Design efficient user interfaces with the <strong>Less is More</strong> principle</li>
<li>Tie your new skills together into one unifying principle: <strong>Focus</strong></li>
</ol>
<p>The Python-based <em><strong><a rel="noreferrer noopener" href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" data-type="URL" data-id="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank">The Art of Clean Coding</a></strong></em> is suitable for programmers at any level, with ideas presented in a language-agnostic manner.</p>
<div class="wp-container-1 is-content-justification-center wp-block-buttons">
<div class="wp-block-button has-custom-width wp-block-button__width-50"><a class="wp-block-button__link" href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank" rel="noreferrer noopener">Get My Book on Amazon!</a></div>
</div>
<hr class="wp-block-separator"/>
<h2>Related Tutorials</h2>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-return-string-from-function/" data-type="post" data-id="784920" target="_blank">Python Return String From Function</a></li>
<li><a href="https://blog.finxter.com/python-return-dictionary-from-function/" data-type="post" data-id="34362" target="_blank" rel="noreferrer noopener">Python Return Dict From Function</a></li>
<li><a href="https://blog.finxter.com/python-return-set-from-function/" data-type="post" data-id="34346" target="_blank" rel="noreferrer noopener">Python Return Set From Function</a></li>
</ul>
<h2>Programmer Humor</h2>
<pre class="wp-block-preformatted has-global-color-8-background-color has-background"><code><strong>Q</strong>: How do you tell an introverted computer scientist from an extroverted computer scientist? <strong>A</strong>: An extroverted computer scientist looks at <strong><em>your</em></strong> shoes when he talks to you.</code></pre>
</div>
https://www.sickgaming.net/blog/2022/10/...in-python/