By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,995 Members | 1,217 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,995 IT Pros & Developers. It's quick & easy.

searching for character in file

P: 31
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
Share this Question
Share on Google+
5 Replies

P: 31
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

Expert 100+
P: 469
That function works fine for me. Maybe you could post your test program.
Mar 9 '09 #3

P: 31
file_name("file url" , "character")

thats how i tested it
Mar 9 '09 #4

P: 126
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

Expert 100+
P: 469
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.