this is my first message here, I hope I will not commit any mistake.

I am writing a python 2.7 script which performs comparisons between lines from a long list of lines provided as an external input file. Some of these lines contain just numbers, and on those I perform simple sums after their retrieval via getline.linecache.

My problem is that after a certain number of lines I am getting the error:

ValueError: invalid literal for int() with base 10

I do understand that somehow this has to do with the fact that there is some problem when I try to convert the lines retrieved to the integer type, but according to what I read each line should be retrieved from a memory database as a string, and indeed if I try to print the type of the values retrieved I get str. I printed the problematic values in order to understand why they failed to be converted to int: at first i included some semantic mistakes (I was taking some wrong lines, which were containing letters, and this of course failed to be converted to int), but still I get the error on merely numerical strings. On all of those numerical strings, I tried len(linecache.getline('input', line_n)) to see if any extra characters were present, but I just found '\n', which does not give any problems when converting from str to int.

My input file is made by a series of lines, some numerical some not; here are few lines:

1
id3021-a
1
129485768
129485769
2
id2034
102
944709842
944709848

For examples, line 4 here can be retrieved, but not converted to int. How could I convert str to int without getting errors?

有帮助吗?

解决方案

I found the solution! Adding a '0' to the beginning of the string fixes the problem (I do not know why, the problematic lines were not empty):

int('0' + linecache.getline('input', line_n))

See here: Trouble converting string to int in Django/Python

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top