I read a file, containing a list of numbers, (which are some identifiers that I need later).
If there is an empty line at the end of my file, I have a bug in the following code:
return [ int(x) for x in lines if not x == '' and not x == "\r\n"]
with the following python output:
[...]
File "Z:\Projects\PyIntegrate\perforceIntegration.py", line 453, in readChange
ListNumbers
self.changeListNumbers = loadChangeListNumbers()
File "Z:\Projects\PyIntegrate\perforceIntegration.py", line 88, in loadChangeL
istNumbers
return [ int(x) for x in lines if not x == '' and not x == "\r\n"]
ValueError: invalid literal for int() with base 10: ''
obviously my test if not x == '' and not x == "\r\n" is not sufficient for handling this situation.
What do I do wrong ?
(everything is ok if I suppress the last empty line of my file, i.e. if i let the last line of my file containing really a number)
Try this:
This will
stripall spaces and newlines from thelineand if it is not empty (i.e. it contains some characters, preferably numbers), it will convert it intoint.It will however fail (and raise
ValueError) if your file contains other characters than digits or it contains spaces between digits.