2

Is there any way to make sure that a csv, or just any file in general, is loaded into a script? I'm trying to make an interactive menu, and I want to make sure, that the menu options are only running when a valid file has been loaded to the script:

        #Load new data.
        if choice == 1:
            while True:
                filename = input("Please enter .csv filename: ")
                path = os.listdir(os.getcwd())

                #If the file is in the path, the code will run
                if filename in path[:len(path)]:   
                        print("\nData has been loaded!\n")
                        loadcsv = pd.read_csv(filename)
                        break
                else:
                        print("\nFile has not been found.") 

        #Check for errors.
        if choice == 2:
            if filename not in sys.modules:
                print("Please upload a file")
            else:
                pass

Here i tried to use the code:

if choice == 2:
            if filename not in sys.modules:
                print("Please upload a file")
            else:
                pass

But it just says that the filename is not defined.

  • your `input()` statement to get the `filename` is within the `if choice == 1:` block, so `if choice == 2`, there was no `input`, hence there is no variable `filename`. Besides that, the check if the `filename` is in `sys.modules` is probably wrong as well. – Edwin van Mierlo Jan 15 '18 at 14:26

0 Answers0