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.