Connecting Tech Pros Worldwide Forums | Help | Site Map

searching for character in file

Newbie
 
Join Date: Feb 2009
Posts: 31
#1: Mar 9 '09
i'm given an open file, and basically they give you a character(a str) and whenever the occurence of that string appears as the starting word of the line, we are to return that line.

as an example:
the file =

fds dfds kjkj kjkdsf
abc def hij
klm nop qrs
tuv wx yz

and the character given is "klm"

i am to return the line "klm nop qrs"

how would i be able to write this??!!

Newbie
 
Join Date: Feb 2009
Posts: 31
#2: Mar 9 '09

re: searching for character in file


this is what i have so far

Expand|Select|Wrap|Line Numbers
  1. def lines_start_with(f, a):
  2.     for line in f:
  3.         if line.startswith(a):
  4.             print line.strip()
  5.  
the thing is that when i test it it doesn't print out anything :S
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#3: Mar 9 '09

re: searching for character in file


That function works fine for me. Maybe you could post your test program.
Newbie
 
Join Date: Feb 2009
Posts: 31
#4: Mar 9 '09

re: searching for character in file


file_name("file url" , "character")

thats how i tested it
Smygis's Avatar
Member
 
Join Date: Jun 2007
Posts: 100
#5: Mar 9 '09

re: searching for character in file


Expand|Select|Wrap|Line Numbers
  1. >>> l=['fds dfds kjkj kjkdsf', 'abc def hij', 'klm nop qrs', 'tuv wx yz']
  2. >>> for i in l:
  3. ...     if "klm" in i:
  4. ...             print i
  5. ... 
  6. klm nop qrs
  7. >>> 
  8.  
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: California
Posts: 478
#6: Mar 10 '09

re: searching for character in file


You have to pass your function a file object, not the file name. Try something like this:
Expand|Select|Wrap|Line Numbers
  1. my_file = open("my_file.txt")
  2. lines_start_with(my_file, "klm")
I hope this works.
Reply