Search and write to .txt file
Simon Forman
sajmikins at gmail.com
Tue Aug 11 11:44:04 EDT 2009
On Aug 11, 7:22 am, Helvin <helvin... at gmail.com> 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!
There's a bug in this line:
if line.find('1'):
the string find() method returns an integer, which will be -1 if the
substring is not found. In python -1 is treated as True (only 0 is
False) so your if statement will always succeed unless '1' is the
first character on the line.
HTH,
~Simon
P.S. you can use the help() command in the python interpreter to get
docs on most things:
>>> help(str.find)
Help on method_descriptor:
find(...)
S.find(sub [,start [,end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within s[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
More information about the Python-list
mailing list