Python 3的迭代文件

时间:2018-03-22 16:03:44

标签: python python-3.x file iteration

您对此脚本有任何建议吗?

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

代码:

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)

错误:

    if item>=9000:
TypeError: '>=' not supported between instances of 'str' and 'int'

1 个答案:

答案 0 :(得分:1)

由于item位于文本文件中,因此它是一个字符串,您应该在比较之前将其转换为int

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