Help required to read and print lines based on the type of first character
bruno.42.desthuilliers at websiteburo.invalid
Thu Mar 5 18:15:22 CET 2009
Abhinayaraj.Raju at Emulex.Com a écrit :
Please, don't top-post, and learn to quote & snip
(if you don't know what top-posting is, google is your friend).
> 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
> 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
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.
More information about the Python-list