python TypeError:str对象不是迭代器

时间:2014-10-25 12:03:21

标签: python string search printing

我正在编写一个代码,在文本文件中搜索值并打印上一行; 但我遇到了两个问题,首先我没有找到打印前一行的方法,当我编写代码打印下一个值时,我收到了错误。

代码: -

with open('Perfix/prefix.txt') as f:
    lines = f.readlines()
    for line in lines:
        if "100" in line:
            print (next(line))

假设情景: -

代码应该在prefix.txt文件中搜索以找到值为100的行,然后它应该打印上一行。多数民众赞成!!

错误: -

Traceback (most recent call last):
  File "1.py", line 7, in <module>
    print next(line)
TypeError: str object is not an iterator

错误是什么?你也可以建议如何打印&#34;之前&#34;不是下一行?

示例: -

文件prefix.txt

00
122
141
1525
1162
1547
100
125
15321
1100
1513
142100

输出: -

1547

3 个答案:

答案 0 :(得分:3)

查找上一行的最简单方法是,每次匹配时只存储该行:

with open('Perfix/prefix.txt') as f:
    previous = None
    for line in f:
        line = line.strip()
        if line == '100':
            print previous
        previous = line

请注意,您不需要先将所有行读入内存;只是循环遍历文件对象。

next()功能不是你应该在这里使用的东西;它需要一个迭代器并将它推进到 next 项目,而不是将它倒回到前一个条目。

答案 1 :(得分:1)

错误消息是明确的 - linestr,而不是迭代器,因此next(line)毫无意义。考虑:

next('hello')

会发生什么?


为了解决您的问题,我建议如下:

for index, line in enumerate(lines): # get the index for each line as we go
    if index and line.strip() == '100': # if this isn't the first line & is just '100'
        print lines[index-1] # print the previous line
        break # optional - stop iterating if you don't want to find further lines

或成对迭代;见例如Iterate a list as pair (current, next) in Python

另请注意,文件关闭后,您可以执行此操作

 with open(...) as f:
     lines = f.readlines()
 for index, line in enumerate(lines):
     ...

答案 2 :(得分:1)

通过re模块。

#!/usr/bin/python
import re
with open('file', 'r') as f:
    lines = f.read()
    print re.findall(r'(?m)^(.*)\n100$', lines)[0]

<强>输出:

1547

<强>解释

(?m)                     set flags for this block (with ^ and $
                         matching start and end of line) (case-
                         sensitive) (with . not matching \n)
                         (matching whitespace and # normally)
^                        the beginning of a "line"
(                        group and capture to \1:
  .*                       any character except \n (0 or more
                           times)
)                        end of \1
\n                       '\n' (newline)
100                      '100'
$                        before an optional \n, and the end of a
                         "line"