469,315 Members | 1,577 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,315 developers. It's quick & easy.

searching for character in file

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??!!
Mar 9 '09 #1
5 1394
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()
the thing is that when i test it it doesn't print out anything :S
Mar 9 '09 #2
469 Expert 256MB
That function works fine for me. Maybe you could post your test program.
Mar 9 '09 #3
file_name("file url" , "character")

thats how i tested it
Mar 9 '09 #4
126 100+
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. >>> 
Mar 9 '09 #5
469 Expert 256MB
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.
Mar 9 '09 #6

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Adrian | last post: by
17 posts views Thread by AL | last post: by
21 posts views Thread by Umesh | last post: by
3 posts views Thread by Ahmad Jalil Qarshi | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by harlem98 | last post: by
1 post views Thread by Geralt96 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.