[Tutor] Problem with strings
Denis
spirou@aragne.com
Thu, 17 Aug 2000 21:54:03 +0200
Le Thu, Aug 17, 2000 at 02:04:14PM -0400, Daniel D. Laskey, CPA pianota:
> Objective:
> 1) To read a file called "s8288_ps.txt";
> 2) search through the file line by line for the text "Totals for 4I"; and
> 3) send the results of the search line by line to a newfile called "junk2.txt"
>
You can't search for a string in a string using in
You could search for a "char", like this:
if 'h' in 'Python':
print 'hello'
as the error message says :
> TypeError: string member test needs char left operand
but you can't do that
> if 'Totals for 4I' in line:
You could play with the re module.
Since you want to import the string module (why ?), use instead
the string.find() method
--------------------------------
>>> import string
>>> print string.find.__doc__
find(s, sub [,start [,end]]) -> in
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.
---------------------------------
Check your variable a that comes from nowhere
(did you mean a = line ?)
and look out : the indentation here is crucial (out_file.write(a))
You're on the good way !
Denis
> Code:
> # import sys and string
> import sys
> import string
>
> # open the file
> in_file = open("s8288_ps.txt","r")
>
> # create the file you want to export the data to
> out_file = open("junk2.txt","w+")
>
> # read each line in the file
> for line in in_file.readlines():
> # grab each line
> if 'Totals for 4I' in line:
> print a
> # write the new file you created to the file "junk2.txt"
> out_file.write(a)
> out_file.close()
> in_file.close()
>
> Error message:
> Traceback (innermost last):
> File "today4.py", line 15, in ?
> if 'Totals for 4I' in line:
>
> Thanks,
> Dan
> ---------------------------------------------------------------------------------------
> | Daniel D. Laskey, CPA-------------------dlaskey@laskeycpa.com
> | Daniel D. Laskey Company, P.C.------231-723-8305 Voice
> | 231-723-6097 Fax
> | Certified Public Accountants
> | 507 Water Street
> | Manistee, MI 49660
> ---------------------------------------------------------------------------------------
>
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://www.python.org/mailman/listinfo/tutor
--
Denis FRERE
P3B : Club Free-Pytho-Linuxien Caroloregien http://www.p3b.org
Aragne : Internet - Reseaux - Formations http://www.aragne.com