Search code examples
pythonvariablesuser-inputreadfile

opening a python file from input stored in a variable


I am trying to get my program to open and read a text file from what the user inputs stored in the file_name variable, but it doesn't seem to read anything, but does print "File is now open".

def open_sn_file(self):
    while True:
        file_name = input("Please enter a file name or enter 'done' to exit the program: ")

        if file_name == "done":
            print("Bye.")
            break

        try:
            with open(file_name, 'r') as file:
                file.read()
                print("File is now open.")

I tried so many things, still getting the same problem. I am not sure what to do.


Solution

  • first of all, you would need an except or finally after try. Then, it is also better and cleaner to close the file after you are done with, as implemented below. Also, if you want to output the contents of the file in the console, you need to just print it, as done below. The following code below worked successfully for me:
    Like this:

    while True:
        file_name = input("Please enter a file name or enter 'done' to exit the program: ")
    
        if file_name == "done":
            print("Bye.")
            break
    
        try:
            with open(file_name, 'r') as file:
                print("File is now open.")
                print(file.read())
                file.close()
        except:
            print("An exception occurred")
    

    Hope this helps