pythonfileinputoutput

How to write to a user input file name in python


I have to create and write to a file that's named by user input. The user is naming the file so the program cannot have a set file name to open. I thought I could do this by setting an input variable. That creates the file, but then I need to append more user input to a list and write that list to the user's file.

[snip]

Here's a very compressed version. The full version has a while loop with three if statements. I put the writing command outside the loop because trying to put it in the if statement blocks broke it completely.

EDIT I attempted this edit based on feedback but it's still giving me the exception error when trying to write to the file. I'm including more of the code because I'm wondering if it being out of the if statement may be what's giving it the problem?

while True:
       try:
              print("Select:\n1. Create a file\n2. Open a file to add results to\n3. Read results from file")
              choice = int(input())
              break
       except Exception as err:
              print(err)

if choice == 1:
    print("Please enter the name of the file you would like to create (Must include .txt in name):")
    bmiFile = input()
    bmiEntry = open(bmiFile, 'w')
    print("Creating", bmiFile)

    bmiEntry.close()
        #Age entry
    while True:
            try: 
                age = float(input("Please enter your age: "))
                if age <= 0:
                    raise TypeError ("Please enter a number greater than zero.")
                break
            except ValueError:
                    print("Invalid input.")
                    print("Please enter your age in numeric format.")
            except TypeError as err:
                    print(err)
            except:
                    print("Invalid input.")
bmiIndex.append(age)

try:
        bmiEntry = open(bmiFile, 'w')
        for i in bmiIndex:
                bmiEntry.write(i + '\n')
except:
        print('Error writing to file.')
        
bmiEntry.close()

Solution

  • One problem is that you're trying to append a string to a float:

    bmiEntry.write(i + '\n')
    

    This will raise an exception: TypeError: unsupported operand type(s) for +: 'float' and 'str'

    To fix this, we need to convert the float to a string either explicitly or with a format string:

    bmiEntry.write(str(i) + '\n')
    # or ...
    bmiEntry.write(f"{i}\n")
    

    Another problem (from the original question) is that you've redefined the file name (string) to a file object:

    bmiFile = input()
    bmiFile = open(bmiFile, 'w')
    

    This works because Python is flexible that way, but then later you try to open the file using the file object instead of a string:

    open(bmiFile, 'w')
    

    To fix this, you can capture the file name seperately from the file object:

    bmiFileName = input()
    bmiFile = open(bmiFileName, 'w')
    

    Then use the file name to open the file later on in the code:

    open(bmiFileName, 'w')
    

    Alternatively, you could gather the user input first, then create and write the file at once::

    bmi_index = []
    
    while True:
        try: 
            age = float(input("Please enter your age: "))
            if age > 0: break
            print("Invalid input. Please enter a number greater than zero.")
        except ValueError:
            print("Invalid input. Age must be a numeric value.")
        except Exception as ex:
            print(f"Unexpected exception: {ex}")
    
    bmi_index.append(age)
    
    bmi_file_name = input(
        "Please enter the name of the file to create (must end in '.txt'): "
        ).strip()
    
    if not bmi_file_name.endswith(".txt"): 
        bmi_file_name = f"{bmi_file_name}.txt"
    
    with open(bmi_file_name, 'w') as bmi_file:
        for i in bmi_index:
            bmi_file.write(f"{i}\n")