1

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!

1
  • Python does come with some magic - well I mean nice tools - but at a time, you have to implement your logic. If you want to have a concept of rolling 3 rows you will have to implement it. You can use enumerate as a helper because it give you the current index, but beware: the first and last rows are corner cases. Commented Aug 20, 2020 at 12:26

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You It Work
0

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

1 Comment

May I know why this has been downvoted ? Should work perfectly and is accurate to the example given in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.