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!
Put
try:andexcept:around the code, and usepassin theexcept:block to ignore the error