Home > other >  How to add a try & except construct so that the script ignores that there is no file
How to add a try & except construct so that the script ignores that there is no file

Time:10-07

I don't really know the Python language, so I'm asking for help from experts. I have a simple script and I need to add a construct to it

try:
except:

this is necessary so that the script ignores that there is no 'file.txt' file and does not display an error.

If the file "file.txt" is missing, the script.py script displays the following error:

Version 1.2.1.
Traceback (most recent call last):
  File "script.py", line 10, in <module>
    with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

How can I make the script ignore that there is no 'file.txt' and not throw this errorTraceback (most recent call last) ?

Script code:

import sys

if __name__ == '__main__':
    if '-v' in sys.argv:
        print(f'Version 1.2.1.')


h = format(0x101101, 'x')[2:]

with open("file.txt") as myfile, open("save.txt", 'a') as save_file:

    for line in myfile:
        if h in line:
            save_file.write("Number = "   line   "")
            print("Number = "   line   "")

Help how to add a try & except construct to it? Thanks in advance for your help!

CodePudding user response:

Put try: and except: around the code, and use pass in the except: block to ignore the error

try:
    with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
        for line in myfile:
            if h in line:
                save_file.write("Number = "   line   "")
                print("Number = "   line   "")
except FileNotFoundError:
    pass

CodePudding user response:

You do the try: and then have the indented-block of code you want to try and if the error is raised, it'll go to that except: block of code and do whatever you want there.

try:
    with open("file.txt") as myfile, open("save.txt", 'a') as save_file:
        for line in myfile:
            if h in line:
                save_file.write("Number = "   line   "")
                print("Number = "   line   "")
except FileNotFoundError:
    print("The error was found!")
    # or do whatever other code you want to do, maybe nothing (so pass)
    # maybe let the user know somehow, maybe do something else.
    

CodePudding user response:

try:
   with open("file.txt") as myfile, open("save.txt", 'a') as save_file:

    for line in myfile:
        if h in line:
            save_file.write("Number = "   line   "")
            print("Number = "   line   "")
except NameError:
   print("file doesn't exist")
finally:
   print("regardless of the result of the try- and except blocks, this block will be executed")
  • Related