-1

Do you have any suggestions for this script?

file.txt:

17
1
11
1
13
15
11
5
7
21
19
17
13
19
11
7
1
3
5
3
11
9
7
15
13
21
19
17
27
25
23
9001
9003
9023
9044
9055
9007

Code:

l2=[]
with open("file.txt") as f:
    data = f.read()
    l1 = list(data.split('\n'))
    for item in l1:
        if item>=9000:
            l2.append(item)
        else:
            item = item+9000
            l2.append(item)
print(l2)

Error:

    if item>=9000:
TypeError: '>=' not supported between instances of 'str' and 'int'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Pydavide
  • 59
  • 4
  • 2
    Possible duplicate of [How to convert strings into integers in Python?](https://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python) – jonrsharpe Mar 22 '18 at 16:04
  • Just run in Python 2, it will happily perform the comparison (and output the wrong answer!) ;) – Chris_Rands Mar 22 '18 at 16:14

1 Answers1

1

Since item is in a text file, it is a string, you should convert it to an int before comparing:

for item in l1:
    if item.isdigit():  # if it is a number
        item = int(item)  # convert it to int
        if item>=9000:
            l2.append(item)
        else:
            item = item+9000
        l2.append(item)
    else:  # not a number
        # do something
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • Returns this error ValueError: invalid literal for int() with base 10: '' – Pydavide Mar 22 '18 at 18:23
  • @Pydavide That may be caused by having something else in the file that is not a number, anyway, in my last edit I first see if the string is a representation of a number before converting it. It should work now. – DjaouadNM Mar 22 '18 at 18:31
  • @Pydavide Great. You should mark answers that you see best as 'correct'. – DjaouadNM Mar 22 '18 at 19:27