此Python代码运行,但打印文本文件的最后一页。不知道为什么,但是我的目的是打印指定文本行(包含特定字符串** Direct **的行)下方的整行文本。如何遍历文本文件,在每一行中搜索指定的字符串,并在找到后立即在其下方打印行?我搜索了许多在线论坛,但没有找到一个易于理解的示例。我使用Python Sypder 2.7。任何帮助表示赞赏
import os
Path = '..\\Test.txt'
if os.path.isfile(Path):
with open(Path) as f:
for line in f:
print line
else:
print Path, "doesn't exist"
f.close()
答案 0 :(得分:1)
Python 3.x:
dummy.txt
Mango
Anday Wala Burger
40
Aloo
Anday
Ghobi
Anday Wala Burger
30
Kheerey
Anday Wala Burger
py:
searchString = 'Anday Wala Burger'
with open('dummy.txt', "r") as input:
try:
for line in input:
if searchString in line:
print(next(input), end='')
except StopIteration:
pass
输出:
40
30
编辑:
Python 2.7:
dummyFile= "dummy.txt"
searchString = 'Anday Wala Burger'
with open(dummyFile) as f:
content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
# flag
nextLine = False
for line in content:
if searchString in line:
nextLine = not nextLine
else:
if nextLine:
print(line)
nextLine = not nextLine
else:
pass
输出:
40
30
答案 1 :(得分:0)
检出re
模块。它包含re.search()
函数,该函数在字符串中搜索模式。
要打印下一行,可以使用f.next()
来利用文件对象可迭代的事实。
例如,您可以这样做:
import os
import re
Path = 'foo.txt'
Pattern = "spam" # String to be searched
if os.path.isfile(Path):
with open(Path) as f:
for line in f:
if re.search(Pattern, line):
print(f.next())
else:
print(Path, "doesn't exist")
顺便说一句,您不需要最后的f.close()
。 with
语句已经解决了这个问题。
答案 2 :(得分:0)
检查one
是否在文件的任何行中,并将找到的下一行打印为下一行,将打印的下一行打印为currentlineno+1
文件临时目录的内容
one
two
three
four
Python文件
with open('temp') as f:
found=-1
#no lines are found to print so found is negative in value since line no in a file cannot be negative
for index,line in enumerate(f):
if found==index:
print(line)
if 'one' in line:
found=index+1
# when the condition is True found is set to the line no that we need to print
输出
two
答案 3 :(得分:0)
您需要进行一些更改:
1.-阅读各行
2.-与您的文字进行比较
import os
Path = '..\\Test.txt'
look='**Direct**'
if os.path.isfile(Path):
with open(Path, "r") as f:
for line in f:
if look in line:
print (line)
else:
print (Path, "doesn't exist")