Home > Software design >  How can I make python script show an error when user inputs same file name with this piece of code?
How can I make python script show an error when user inputs same file name with this piece of code?

Time:11-05

I was creating a note taking program, using the user voice command. When the file already exists, I want to show an error. It runs smoothly when the file name is different though. When the file already exists, I have coded to open in the writing mode. It would erase the earlier file, and write new instead of adding in the append mode.

elif 'note' in query:
            try:
                speak(" Okay master. what's the file name")
                b= takecommand()
                f = open(f"{b}.txt","w")
                speak("Okay master. tell me what to note down")
                a= takecommand()
                f.write(f"{a}\n")
                f.close()
            except Exception as e:
                speak("file name already exist")

Can you help me with troubleshooting the script? Like how could I first make it thrown an error when the filename is same?

CodePudding user response:

You'd want to check if the file exists after they input it, which can be done using "os.path.exists" as also suggested by Tim Roberts. Here's code that should work for you:

elif 'note' in query:
        try:
            Looper = True # Added a loop so it can repeatedly ask the user until they give a valid answer.
            speak(" Okay master. what's the file name") # Put here instead of in the loop so it will repeat once since the else condition already asks for a new file name aswell.
            while Looper == True:
                b = takecommand()
                if os.path.exists(f"{b}.txt"):
                    f = open(f"{b}.txt","w")
                    speak("Okay master. tell me what to note down")
                    a= takecommand()
                    f.write(f"{a}\n")
                    Looper = False # So the loop won't repeat again (regardless of the below line).
                    f.close()
                else:
                    speak("That file already exists. Give me a new file name.")
        except Exception as e:
            speak("Hm, an error occured. Try again later.")

I also added in a while loop for you, so that way if the user gives a file name that already exists, it will keep asking until they give a valid file name.

Ensure you have OS imported for the code to work by adding the following to the top of your code:

import os

CodePudding user response:

Use mode 'x'

x' create a new file and open it for writing. The 'x' mode implies 'w' and raises an FileExistsError if the file already exists.

try:
    # ...
    f = open(f"{b}.txt","x")
    # ...
except FileExistsError:
    speak("file name already exist")

Or mode 'a' to append the strings to existing file.

'a' open for writing, appending to the end of the file if it exists

  • Related