Home > Mobile >  Python how to change formatting of an input when calling a function a second time
Python how to change formatting of an input when calling a function a second time

Time:04-10

I am trying to code this function so that it gets called twice. On the first time it is called, s should be a string 'JSON', and the second time it is called, s should be a different string 'txt'. The goal is that so when the function is called the first time it will ask: "Enter a JSON file" and the second time it should prompt "Enter a txt file"

def open_file(s):
    test1 = False
    while not test1:
       file_name = input("Enter a {} file name: ".format(s))
       try:
           fp = open(file_name, 'r')
           test1 = True
           return(fp)
       except FileNotFoundError:
           print("File not found.  Try again.")

CodePudding user response:

I am almost sure that you shouldn't do that! I guess you have control over calling it so you could just add extra parameter for your function and based on it decide whether is it JSON or TXT. Saying that, if you don't mind do some ugly things, you could use decorator:

def deco(fun):
    def f(s):
        f.no_calls  = 1
        fun(s, f.no_calls)

    f.no_calls = 0
    return f


@deco
def open_file(s, no_calls): # no_calls parameter will be provided by decorator
    if no_calls == 1:
        print("JSON")
    if no_calls == 2:
        print("TXT")

# you call it without second parameter
open_file("") # JSON
open_file("") # TXT

CodePudding user response:

I'm not exactly sure you understand the principles of file handling. You said the goal was to initially get a "Enter a JSON file" and a "Enter a txt file" message. However, your try and except handling isn't working correctly. You're printing "File not found. Try again", but there is no again. The code just stops working since there's no loop or recurrence. This is some code I think will be helpful:

s=('JSON', 'txt')

def check_json(s):
    file_name = input("Enter a {} file name: ".format(s[0]))
    try:
        fp = open(file_name, 'r')
    except FileNotFoundError:
        print("File not found. Try again.")
    return check_json(s)
    
def check_txt(s):
    file_name = input("Enter a {} file name: ".format(s[1]))
    try:
        fp = open(file_name, 'r')
    except FileNotFoundError:
        print("File not found. Try again.")
    return check_txt(s)

check_json(s)
check_txt(s)

You wanted a variable s even though it could've been done without that and without the format() method. It can obviously be done without functions as well.

I hope this clears things up in terms of changing the format of an input in a function

  • Related