Read Line By Line And Get The Previous And The Next Lines
I'm trying to read a file line by line and get every current, previous and next line. Eg: line1 line2 line3 line4 What I'd like is: None, line1, line2 line1, line2, line3 line2, l
Solution 1:
next(f)
consumes the next line, each line can only be read once, so you need to reorder how you read lines. This should work
withopen(filename) as f:
previous =Nonecurrent= next(f).strip()
for line in f:
line=line.strip()
print(previous, current, line)
previous =currentcurrent= line
Output:
None line1 line2
line1 line2 line3
line2 line3 line4
Solution 2:
The issue that you're encountering is that next(f)
iterates the file position, so for each iteration of the for
loop, two lines are actually being read.
You can accomplish this by changing your approach slightly. Instead of line
being the center element, you should have line
refer to the last element, and maintain previous-previous
as well as previous
.
prevprev = Nonewithopen(filename, 'r') as f:
# Read the first line before the loop
prev = f.readline().strip()
for line in f:
line = line.strip()
print(prevprev, prev, line)
prevprev = prev
prev = line
Output:
None line1 line2
line1 line2 line3
line2 line3 line4
Solution 3:
lines = [None, None, None]
with open(filename, 'r') as f:
for line in f:
lines[0] = lines[1]
lines[1] = lines[2]
lines[2] = line.strip()
iflines[1] andlines[2]:
print(', '.join([str(l) for l inlines]))
Solution 4:
You could use a simple for loop:
withopen('test.txt', 'r') as f:
data = [None]+f.read().split('\n')
size = 3for i inrange(len(data)-(size-1)):
print(data[i:i+size])
Solution 5:
I'd use slices of lists:
withopen(filename) as f:
xs = [None]*3for x in f:
xs = xs[1:] + [x]
print xs
outputs:
[None, None, 'line1\n'][None, 'line1\n', 'line2\n']['line1\n', 'line2\n', 'line3\n']['line2\n', 'line3\n', 'line4\n']['line3\n', 'line4\n', 'line5\n']
Cleaning up to match your exact output format:
withopen(filename) as f:
xs = ['None']*2 + [f.next().strip()]
for x in f:
xs = xs[1:] + [x.strip()]
print', '.join(xs)
outputs:
None, line1, line2
line1, line2, line3
line2, line3, line4
line3, line4, line5
Post a Comment for "Read Line By Line And Get The Previous And The Next Lines"