Python code to ignore errors

2024/11/19 6:15:30

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 tldextractdef main(argv):in_file = argv[1]f = open(in_file,'r')urlList = f.readlines()f.close()destList = []for i in urlList:print istr0 = ifor 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

Answer

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 systry: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', argelse: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.

https://en.xdnf.cn/q/118573.html

Related Q&A

How to match background color of an image with background color of Pygame? [duplicate]

This question already has an answer here:How to convert the background color of image to match the color of Pygame window?(1 answer)Closed 3 years ago.I need to Make a class that draws the character a…

Sharepoint/SOAP - GetListItems ignoring query

Trying to talk from Python to Sharepoint through SOAP.One of the lists I am trying to query contains ID as primary key field.(Field){_RowOrdinal = "0"_FromBaseType = "TRUE"_DisplayN…

python mean between file

I create a list of more than a thousand file (Basically now I have a list with the name of the file) now in order to make the man I thought to do something like this (suppose asch file have 20 lines): …

Sort a dictionary with custom sorting function

I have some JSON data I read from a file using json.load(data_file){"unused_account":{"logins": 0,"date_added": 150},"unused_account2":{"logins": 0,&qu…

Turtle make triangle different color

Hi guys Im trying to replicate this image:Its almost done I just have one issue, where the triangle is supposed to be yellow it isnt seeming to work.Mine:Code:fill(True) fillcolor(green) width(3) forwa…

How to DataBricks read Delta tables based on incremental data

we have to read the data from delta table and then we are joining the all the tables based on our requirements, then we would have to call the our internal APIS to pass the each row data. this is our g…

Converting an excel file to a specific Json in python using openpyxl library with datetime

I have the Excel data with the format shown in the image preview. How can I convert it into a JSON using Python? Expected Output: file_name = [ { A: Measurement( calculated_date=datetime(2022, 10, 1, …

How to find a word in a string in a list? (Python)

So im trying to find a way so I can read a txt file and find a specific word. I have been calling the file with myfile=open(daily.txt,r)r=myfile.readlines()that would return a list with a string for ea…

How to make a new default argument list every time [duplicate]

This question already has answers here:The Mutable Default Argument in Python(34 answers)Closed 10 years ago.I have the following setup:def returnList(arg=["abc"]):return arglist1 = returnLis…

How does one reorder information in an XML document in python 3?

Lets suppose I have the following XML structure:<?xml version="1.0" encoding="utf-8" ?> <Document><CstmrCdtTrfInitn><GrpHdr><other_tags>a</other_t…