0

I want to set the current position in a textfile one line back.

Example:

I search in a textfile for a word "x".

Textfile:

  1. Line: qwe qwe
  2. Line: x
  3. Line: qwer
  4. Line: qwefgdg

If i find that word, the current position of the fobj shall be set back one line. ( in the example I find the word in the 2. Line so the position shall be set to the beginning of the 1. Line)

I try to use fseek. But I wasn't that succesfull.

Peter
  • 1,629
  • 2
  • 25
  • 45
  • This might help, [make a python iterator go backwards](http://stackoverflow.com/questions/2777188/making-a-python-iterator-go-backwards) – Greg Sep 09 '13 at 06:56
  • I did like here. http://stackoverflow.com/questions/3505479/python-undo-a-python-file-readline-operation-so-file-pointer-is-back-in-origi – Peter Sep 09 '13 at 08:03

2 Answers2

2

This is not how you do it in Python. You should just iterate over the file, test the current line and never worry about file pointers. If you need to retrieve the content of the previous line, just store it.

>>> with open('text.txt') as f: print(f.read())
a
b
c
d
e
f

>>> needle = 'c\n'

>>> with open('test.txt') as myfile:
    previous = None
    position = 0
    for line in myfile:
        if line == needle:
            print("Previous line is {}".format(repr(previous)))
            break
        position += len(line) if line else 0
        previous = line

Previous line is 'b\n'

>>> position
4

If you really need the byte position of the previous line, be aware that the tell/seek methods don't blend well with iteration, so reopen the file to be safe.

Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
0
f = open('filename').readlines()
i = 0
while True:
   if  i > range(len(f)-1):
       break
   if 'x' in f[i]:
      i = i - 1
   print f[i]
   i += 1

Be careful as that will create a forever loop. Make sure you enter an exit condition for loop to terminate.

duck
  • 2,483
  • 1
  • 24
  • 34