![]() |
|
[Tut] How to Return a File From a Function in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Return a File From a Function in Python? (/thread-100120.html) |
[Tut] How to Return a File From a Function in Python? - xSicKxBot - 10-21-2022 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 keywordoperation Code: return open(filename, mode='r')Here’s a minimal example that tries to open a filename that was provided by the user via the Code: input()Code: 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: code.py ):Code: 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 Code: returnCode: 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: Code: 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.
The Python-based The Art of Clean Coding is suitable for programmers at any level, with ideas presented in a language-agnostic manner. Get My Book on Amazon! Related Tutorials Programmer Humor Code: 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. |