Reading sub-string from a file

Peter Otten __peter__ at web.de
Thu Feb 16 11:25:49 CET 2012


Smiley 4321 wrote:

> I am a python newbie.

Welcome!
 
> Let's say I have a filename (test.conf) as below -
> 
> ----
> int Apple(int, int);
> void Jump_OnUnload(float, int);
> int Jockey_Apple_cat_1KK(float, int, char, int);
> int Jockey_Apple_cat_look(int, float, int, int);
> int Jockey_Apple_cat_test_ki21es(int, int, int, int);
> int Jockey_Apple_cat_tarLK12OU(void, int, int, int);
> ---
> 
> Here substring "Jockey_Apple_cat" is common from 3rd line onwards as a
> function name. I wish to extract ONLY that function name which has
> 'Jockey_Apple_cat' as a substring and ignore remaining function names.
> 
> The program .py written is -
> 
> -----
> ---
> #!/usr/bin/python
> 
> def foo(filename):
>         try:
>                 one = open(filename, 'r')
>         except:
>                 print filename, 'cannot be open.'
> 
>         AllLines = one.readline()
> 
>         for eachLine in AllLines:
>                 start = eachLine.find('Jockey_Apple_cat')
>                 if start != -1:
>                         finish = eachLine.find ('(')
>                         print eachLine[start:finish]
> 
>         handle.close()
> 
> set_foo("test.conf")
> -----
> 
> I did perform debugging using pdb, it only reads all the lines.

There are errors in the above that suggest that you retyped your actual 
code. Don't do that! Always use cut and paste for code snippets you are 
posting here.

As to what the problem in your actual code might be, here's a hint:
You could be iterating over the characters of the first line of the file 
instead of the lines. Change

>         AllLines = one.readline()
> 
>         for eachLine in AllLines:

to 

for eachLine in one:

to fix that.




More information about the Python-list mailing list