0

I am trying to edit a text file using fileinput.input(filename, inplace=1) The text file has say 5 lines:

line 0
line 1
line 2 
line 3
line 4

I wish to change data of line 1 based on info in line 2. So I use a for loop

infile = fileinput.input(filename, inplace=1)
for line in infile:
 if(line2Data):
   #do something on line1
   print line,
 else:
   line1=next(infile)
   line2=next(infile) 
   #do something with line2

Now my problem is after the 1st iteration the line is set to line2 so in 2nd iteration the line is set to line3. I want line to be set to line1 in 2nd iteration. I have tried line = line but it doesn't work. Can you please let me know how I am reset the iteration index on line which gets changed due to next

PS: This is a simple example of a huge file and function I am working on.

Jonas
  • 121,568
  • 97
  • 310
  • 388
BitsNPieces
  • 91
  • 1
  • 7

2 Answers2

0

As far as I know (and that is not much) there is no way in resetting an iterator. This SO question is maybe useful. Since you say the file is huge, what I can think of is to process only part of the data. Following nosklos answer in this SO question, I would try something like this (but that is really just a first guess):

while True:
    for line in open('really_big_file.dat')
        process_data(line)
        if some_condition==True:
            break

Ok, your answer that you might want to start from the previous index is not captured with this attempt.

Community
  • 1
  • 1
Moritz
  • 5,130
  • 10
  • 40
  • 81
0

There is no way to reset the iterator, but there is nothing stopping your from doing some of your processing before you start your loop:

infile = fileinput.input("foo.txt")

first_lines = [next(infile) for x in range(3)]
first_lines[1] = first_lines[1].strip() + " this is line2 > " + first_lines[2]
print "\n".join(first_lines)

for line in infile:
    print line

This uses next() to read the first 3 lines into a list. It then updates line1 based on line2 and prints all of them. It then continues to print the rest of the file using a normal loop.

For your sample, the output would be:

line 0

line 1 this is line2 > line 2 

line 2 

line 3

line 4

Note, if your are trying to modify the first lines of the file itself, rather than just display it, you would need to write the whole file to a new file. Writing to a file does not work like in a Word processor where all the lines move down when a line or character is added. It works as if you were in overwrite mode.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97