KrisHnA
KrisHnA

Reputation: 65

How to Print Previous Row And Next Row In python List

I want to print next and previous row , Here is my code

import csv
file= "myfile.txt"
searchname=input("Enter the name to be searched:")
f=open(file,'r')
reader=csv.reader(f)
lst=[]
for row in reader:
    lst.append(row)
    q=0
for row in lst:    
    if searchname in row:
        print(row)
        q+=1
    
f.close()

myfile.txt :

python,programming
java,programming
html,webdesigning
php,programming

I can Search "html" in python : The Output is ['html','webdesigning']
But I want to print
['java','programming']
['html','webdesigning']
['php','programming']



It is Possible?? Anyone Have an Answer?? pls help!

Upvotes: 1

Views: 634

Answers (2)

TheFaultInOurStars
TheFaultInOurStars

Reputation: 3608

you can do this:

for index,row in enumerate(list):
if searchname in row:
    print(row)
    if index - 1 >= 0:
        print(list[index-1])
    if index + 1 < len(list):
        print(list[index+1])

Upvotes: 1

Orsiris de Jong
Orsiris de Jong

Reputation: 3016

csv.reader provides a generator, so you can't just use it like a list. An easy way to achieve what you want should be to transform the reader object as list. You can then iterate over it, and when pattern is found, show the objects with current index -1, 0 and +1.

The try except statement handles the case where your found object is first or last.

import csv

file = "myfile.txt"
searchname = input("Enter the name to be searched:")
with open(file, 'r') as f:
    reader = list(csv.reader(f))
    for index, row in enumerate(reader):
        if searchname in row:
            for i in range(-1, 2):
                try:
                    print(reader[index+i])
                except IndexError:
                    pass

Upvotes: 0

Related Questions