Ways to read/edit multiple lines in python
edit, lines, python
Solution
you could do:
with open(filec , 'r') as f:
lines = f.readlines() # readlines creates a list of the lines
to access line 4 and do something with it you would access:
lines[3] # as lines is a list
and for line 2
lines[1] # etc.
You could then write your lines back into a file if you wish
EDIT:
Regarding your comment, perhaps something like this:
def change_lines(fileC):
with open(fileC , 'r') as f:
while True:
lines = []
for i in range(4):
try:
lines.append(f.next()) # f.next() returns next line in file
except StopIteration: # this will happen if you reach end of file before finding 4 more lines.
#decide what you want to do here
return
# otherwise this will happen
lines[2] = lines[4] # or whatever you want to do here
# maybe write them to a new file
# remember you're still within the for loop here
EDIT:
Since your file divides into fours evenly, this works:
def change_lines(fileC):
with open(fileC , 'r') as f:
while True:
lines = []
for i in range(4):
try:
lines.append(f.next())
except StopIteration:
return
code code # do something with lines here
# and write to new file etc.
Problem
What i'm trying to do is to take 4 lines from a file that look like this: ``` @blablabla blablabla #this string needs to match the amount of characters in line 4 !blablabla blablabla #there is a string here ``` This goes on for a few hundred times. I read the entire thing line by line, make a change to the fourth line, then want to match the second line's character count to the amount in the fourth line. I can't figure out how to "backtrack" and change the second line after making changes to the fourth. ``` with fileC as inputA: for line1 in inputA: line2 = next(inputA) line3 = next(inputA) line4 = next(inputA) ``` is what i'm currently using, because it lets me handle 4 lines at the same time, but there has to be a better way as causes all sorts of problems when writing away the file. What could I use as an alternative?