Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Return a File From a Function in Python?

#1
How to Return a File From a Function in Python?

5/5 – (1 vote)

Do you need to create a function that returns a file but you don’t know how? No worries, in sixty seconds, you’ll know! Go! ?

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 keyword operation return open(filename, mode='r').

Here’s a minimal example that tries to open a filename that was provided by the user via the input() function. If it fails, it prints an error message and asks for a different user input:

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())

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.py—the code reads itself (meta ?):

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())

Note that you can open the file in writing mode rather than reading mode by replacing the line with the return statement with the following line:

open(filename, mode='w')

A more Pythonic way, in my opinion, is to follow the single-responsibility pattern whereby a function should do only one thing. In that case, provide the relevant input values into the function like so:

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()) 

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. Unix style.


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:


The Art of Clean Code



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.

  1. Concentrate on the important stuff with the 80/20 principle — focus on the 20% of your code that matters most
  2. Avoid coding in isolation: create a minimum viable product to get early feedback
  3. Write code cleanly and simply to eliminate clutter
  4. Avoid premature optimization that risks over-complicating code
  5. Balance your goals, capacity, and feedback to achieve the productive state of Flow
  6. Apply the Do One Thing Well philosophy to vastly improve functionality
  7. Design efficient user interfaces with the Less is More principle
  8. Tie your new skills together into one unifying principle: Focus

The Python-based The Art of Clean Coding is suitable for programmers at any level, with ideas presented in a language-agnostic manner.


Related Tutorials


Programmer Humor


Q: How do you tell an introverted computer scientist from an extroverted computer scientist? A: An extroverted computer scientist looks at your shoes when he talks to you.


https://www.sickgaming.net/blog/2022/10/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Async Function xSicKxBot 0 1,276 05-08-2023, 04:28 AM
Last Post: xSicKxBot
  [Tut] How to Create and Run a Batch File That Runs a Python Script? xSicKxBot 0 1,240 11-09-2022, 09:53 PM
Last Post: xSicKxBot
  [Tut] Python Create JSON File xSicKxBot 0 1,252 11-03-2022, 01:09 PM
Last Post: xSicKxBot
  [Tut] How to Filter Data from an Excel File in Python with Pandas xSicKxBot 0 1,225 10-31-2022, 05:36 AM
Last Post: xSicKxBot
  [Tut] What’s the Difference Between return and break in Python? xSicKxBot 0 1,299 10-23-2022, 01:46 AM
Last Post: xSicKxBot
  [Tut] Python – Return NumPy Array From Function xSicKxBot 0 1,186 10-16-2022, 03:49 AM
Last Post: xSicKxBot
  [Tut] Python Return String From Function xSicKxBot 0 1,200 10-14-2022, 01:13 PM
Last Post: xSicKxBot
  [Tut] How to Delete a Line from a File in Python? xSicKxBot 0 1,216 09-24-2022, 10:31 AM
Last Post: xSicKxBot
  [Tut] How to Apply a Function to a List xSicKxBot 0 1,248 09-13-2022, 07:21 PM
Last Post: xSicKxBot
  [Tut] How to Convert a Log to a CSV File in Python? xSicKxBot 0 1,291 08-30-2022, 02:11 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016