changing some lines in a file
Gordon McMillan
gmcm at hypernet.com
Tue Jul 6 10:43:47 EDT 1999
Peter Posselt Vestergaard writes:
> Hi, I'm quite a newbie in Python-programming, so I hope you'll
> forgive me asking about some pretty things. :-) My problem is that I
> have a file in which i want to find some lines and replace them with
> some other data. I've tried a lot of things but nothing seems to
> work.
Unfortunately, you haven't said what "doesn't work" means.
> Below is my best try, but it seems that the script stops when
> it is about to execute the line:
Stops how? With a traceback?
> line=('fi='+Form["fi"].value)
>
> I'll be thankfull for any kind of help.
> Best regards
>
> Peter Vestergaard
>
> ------------------------------------------------------------------
>
>
> db = open("db.dat","r+")
Why are you opening for update?
> data = db.readlines()
> db.close
MIssing something?
>
> found=0
> for line in data:
> print found
> if found==1:
> if line[0:2]=='fi':
> line=('fi='+Form["fi"].value)
Ah. Well you'll never see any results, because you're rebinding the
variable "line" to a new string. When you return to the "for", you
lose all your hard work.
You can either modify the data list by using
for i in range(len(data)):
line = data[i]
.....
data[i] = 'fi=' + Form[whatever]....
Or create a new list and append the modified lines to it.
(Updating a file in place usually means lots of seek()s and tells()
and is basically never worthwhile on text files.)
> elif line[0:2]=='la':
> line='la='+Form["la"].value
> elif line[0:2]=='em':
> line='em='+Form["em"].value
> elif line[0:2]=='ho':
> line='ho='+Form["ho"].value
> elif line[0:2]=='st':
> line='st='+Form["st"].value
> found=2
> if line[0:9]==('id='+Form["id"].value):
> found=1
> if found==0:
> print '<H1>Fejl i årskortnummeret!</H1>'
> stop
>
> db = open("db.dat","w")
> db.writelines(data)
> db.close
>
> --
> http://www.python.org/mailman/listinfo/python-list
- Gordon
More information about the Python-list
mailing list