Python code to ignore errors - python

I have a code that stops running each time there is an error.
Is there a way to add a code to the script which will ignore all errors and keep running the script until completion?
Below is the code:
import sys
import tldextract
def main(argv):
in_file = argv[1]
f = open(in_file,'r')
urlList = f.readlines()
f.close()
destList = []
for i in urlList:
print i
str0 = i
for ch in ['\n','\r']:
if ch in str0:
str0 = str0.replace(ch,'')
str1 = str(tldextract.extract(str0))
str2 = i.replace('\n','') + str1.replace("ExtractResult",":")+'\n'
destList.append(str2)
f = open('destFile.txt','w')
for i in destList:
f.write(i)
f.close()
print "Completed successfully:"
if __name__== "__main__":
main(sys.argv)
Many thanks

You should always 'try' to open files. This way you can manage exceptions, if the file does not exist for example. Take a loot at Python Tutorial Exeption Handling
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
or
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
Do not(!) just 'pass' in the exception block. This will(!) make you fall on your face even harder.

Where ever your error(s) is happening you can wrap it in a try/except block
for i in loop:
try:
code goes here...
except:
pass

Related

How to split input arguments in Python

I have the below code which expects 1 or more file names as arguments.
It works for one file but now the input arguments can be multiple files such as 1.json 2.json 3.json.
How can I handle this?
import sys
import os
import json
inFile = sys.argv[1]
print(inFile)
with open(inFile, 'r') as file:
try:
json_data = json.load(file)
except ValueError as e:
print "Invalid Json supplied:%s" % e
exit(1)
else:
print "json file ok"
print(json_data)
Since argv is a list (parsing the passed arg string is done for you), you can iterate over it, skipping argv[0] which is the program filename:
import json
import sys
for arg in sys.argv[1:]:
with open(arg, "r") as file:
try:
json_data = json.load(file)
print "json file ok"
print json_data
except ValueError as e:
print "Invalid JSON supplied: %s" % e
exit(1)
You may want to put this data into a list so you can do something with it in your program:
import json
import sys
data = []
for arg in sys.argv[1:]:
with open(arg, "r") as file:
try:
data.append(json.load(file))
except ValueError as e:
print "Invalid JSON supplied: %s" % e
exit(1)

How do I tell a user where the line error occurred?

I'm trying to incorporate enumerate so I can give the user of the program where the line error was and the input of that line.
Here is my code:
elif response == 'data2':
print('Processing file:', response + '.txt')
try:
infile = open('data2.txt', 'r')
for line in infile:
amount = float(line)
total += amount
infile.close()
print(format(total, ',.2f'))
except IOError:
print("IO Error occurred trying to read the file.")
except ValueError:
print("Non-numeric data found in file:", response + '.txt')
except:
print("An error occurred.")
As you see I want the ValueErrorto output something along the lines of:
Non-numeric data found in file: data2.txt at line: 3 with input: three
hundred
I'm however stuck on how to accomplish this.
You can use the enumerate built-in function to get the line number:
elif response == 'data2':
print('Processing file:', response + '.txt')
try:
# Python allows you to iterate over a file object directly.
for line_no, line in enumerate(open('data2.txt', 'r')):
amount = float(line)
total += amount
print(format(total, ',.2f'))
except IOError:
print("IO Error occurred trying to read the file.")
except ValueError:
# I took the liberaty of formatting your output in a way
# that's a bit more readble than one long line of text.
print("Non-numeric data found in file: {}.txt at line: {}"
"with input: {}".format(response, line_no + 1, line))
except:
print("An error occurred.")
You need to track what line you are up to in the file, and catch the exception while reading.
for line_number, line in enumerate(infile, 1):
try:
amount = float(line)
except ValueError:
print(
"Non-numeric data found in file",
response + ".txt on line",
line_number,
"with input",
line
)
exit(1) # or whatever is appropriate for this script.

Cannot stop program from crashing with wrong file entered by user

I am creating a program which asks the user to choose a file to run within the program but I can't stop the program from crashing when a file name that does not exist is entered. I have tried try statements and for loops but they have all given an error. The code I have for choosing the file is below:
data = []
print "Welcome to the program!"
chosen = raw_input("Please choose a file name to use with the program:")
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)
Add an exception:
data = []
print "Welcome to the program!"
chosen = raw_input("Please choose a file name to use with the program:")
try:
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)
except IOError:
print('File does not exist!')
Without using an exception you can simply check if the file exists and if not ask for it again.
import os.path
data = []
print "Welcome to the program!"
chosen='not-a-file'
while not os.path.isfile(chosen):
if chosen != 'not-a-file':
print("File does not exist!")
chosen = raw_input("Please choose a file name to use with the program:")
for line in open(chosen):
our_data = line.split(",")
data.append(our_data)
RTM
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise

How does this work: except IOError as e: print("No such file: {0.filename}".format(e))

The code that uses the expression in question:
def read_file(self,file_name):
try:
with open(file_name,'r') as file:
data=file.read()
return data.split()
except IOError as e:
print("Could not read file:{0.filename}".format(e))
sys.exit()
How does this work? What is meaning of {0.filename}.format(e)? Why do we use {0.filename} and not {1.filename}?
This essentially means takes the positional argument at position 0 (in format(e), e is the zero position arg) and grab the filename attribute defined on it:
print("No such file: {0.filename}".format(e))
Is similar to:
print("No such file: {0}".format(e.filename))
It isn't 1.filename because format hasn't been called with an argument at position 1, another example might help you out even more:
print("{0}{1.filename}".format("No such File: ", e))
Here {0} will grab "No such File: " and {1.filename} will grab e.filename and add it to the resulting string.

Getting exception syntax error

I wrote a function. Now I keep getting syntax errors within the try statement. I don't know if its the code I wrote or the try statement
Function:
def connector (links):
for links in infile:
avenues = links.rstrip()
words = []
dct = {}
cord = []
There is more to the code but the error keeps occurring in the try statement, where it says except, any ideas?
try:
infile = open("routes.txt", "r")
links = inf.readlines()
Connector(links)
except LookupError as exceptObj:
print("Error:", str(exceptObj))
connector should be lowercase
You indented wrong
try:
infile = open("routes.txt", "r")
links = inf.readlines()
connector(links)
except LookupError as exceptObj:
print("Error:", str(exceptObj))

Categories

Resources