Help required to read and print lines based on the type of first character
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Thu Mar 5 12:15:22 EST 2009
Abhinayaraj.Raju at Emulex.Com a écrit :
<ot>
Please, don't top-post, and learn to quote & snip
(if you don't know what top-posting is, google is your friend).
</ot>
> Thank you so much for your guidance, Bruno.
>
> This should help me in a long way.
>
> Here is the code I have written.
>
> path = raw_input("\nEnter location eg. c:/buffer/test.txt : \n")
> fileIN = open(path)
This will break if the file can't be opened (doesn't exist, is
protected, whatever).
> count = 0
'count' is used locally in the loop, so it shouldn't be set outside it.
> for line in fileIN:
> data= line
>
> if '####' in data:
> count = 4
> elif '###' in data:
> count = 3
> elif '##' in data:
> count = 2
> elif '#' in data:
> count = 1
> elif data.find('#') == -1:
This test is redundant. if the "'#' in data" evals to False, then
data.find('#') is garanteed to return -1.
> count = 0
>
>
> if (count == 0 and data!=""):
the file iterator yields lines with the newline character included, so
there's no way that data == "" (unless you explicitely remove the
newline character yourself). Read doc for the strip method of string
objects.
Also, you don't need the parens.
> print data + '\nlooks like a code line...\n'
> elif(count== 4):
> print data + '\ninvalid line!\n'
> elif count>=1:
> for i in range(0, count):
> print data
You didn't address my questions wrt/ specs clarifications. There's a
*big* difference between *containing* a substring and *starting with* a
substring. Hint: Python strings have a "startswith" method...
Also and FWIW, since Python >= 2.5.2 (and possibly >= 2.5.0 - I let you
check the docs), Python's strings have a count method too.
Your code is not too bad for a beginner - I've done worse when I started
-, but it doesn't really matches the specs (which is impossible FWIW
given the ambiguities they contain, cf my previous post), and contains a
couple of more or less useless or redundant tests which make it looks a
bit like "programming by accident", and doesn't really uses Python's
string handling features.
HTH
More information about the Python-list
mailing list