Helvin wrote:
Hi everyone,
I am writing some python script that should find a line which contains
'1' in the data.txt file, then be able to move a certain number of
lines down, before replacing a line. At the moment, I am able to find
the line '1', but when I use f.seek to move, and then rewrite, what I
write goes to the end of the .txt file, instead of being adjusted by
my f.seek.
Do you know what way I should take?
Data.txt is a file of 3 lines:
line1
line2
line3
Code:
with open('data.txt', 'r+') as f:
firstread = f.readlines() # Take a snapshot of initial file
f.seek(0,0) # Go back to beginning and search
for line in f:
print line
if line.find('1'):
print 'line matched'
f.seek(1,1) # Move one space along
f.write('house\n') # f.write overwrites the exact
number of bytes.
break # leave loop once '1' is found
f.seek(0,0) # Go back to beginning, and read
data.txt again
lastread = f.readlines()
print 'firstread is', firstread
print 'lastread is', lastread
This shouldn't be too difficult, but I don't know how. > <
Help appreciated!
You can't mix and match the file iterator "for line in f" with the seek
method. You already have the data in firstread, why not process it from
there, i.e. "for line in firstread". Also look at the docs for the find
method, it doesn't return what you think it does.
--
Kindest regards.
Mark Lawrence.
--
http://mail.python.org/mailman/listinfo/python-list