Having problems with str.find ()
I am trying to use str.find () and it keeps raising an error, what am I doing wrong?
import codecs
def countLOC(inFile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
LOC = 0
for line in inFile:
if line.isspace():
continue
comment = line.find('#')
if comment > 0:
for letter in range(comment):
if not letter.whitespace:
LOC += 1
break
return LOC
if __name__ == "__main__":
while True:
file_loc = input("Enter the file name: ").strip()
try:
source = codecs.open(file_loc)
except:
print ("**Invalid filename**")
else:
break
LOC_count = countLOC(source)
print ("\nThere were {0} lines of code in {1}".format(LOC_count,source.name))
Error
File "C:\Users\Justen-san\Documents\Eclipse Workspace\countLOC\src\root\nested\linesOfCode.py", line 12, in countLOC
comment = line.find('#')
TypeError: expected an object with the buffer interface
a source to share
Use the built-in function open()
instead codecs.open()
.
You are faced with the difference between non-Unicode (Python 3 bytes
, Python 2 str
) and Unicode (Python 3 str
, Python 2 unicode
) strings . Python 3 will not automatically convert between non-Unicode and Unicode like Python 2. Using codecs.open () without a parameter encoding
returns the object that gives bytes
when you read it.
Also, your function countLOC
won't work:
for letter in range(comment):
if not letter.whitespace:
LOC += 1
break
That for the loop it will iterate over numbers from zero to one less than the position '#'
in the string ( letter = 0, 1, 2...
); whitespace
is not an integer method, and even if it is, you are not calling it.
Also, you never increment the LOC unless the string contains #
.
A "fixed" but otherwise correct (and ineffective) version of yours countLOC
:
def countLOC(inFile):
LOC = 0
for line in inFile:
if line.isspace():
continue
comment = line.find('#')
if comment > 0:
for letter in line[:comment]:
if not letter.isspace():
LOC += 1
break
else:
LOC += 1
return LOC
How can I write the function:
def count_LOC(in_file):
loc = 0
for line in in_file:
line = line.lstrip()
if len(line) > 0 and not line.startswith('#'):
loc += 1
return loc
a source to share
Are you passing an open file to a function? Maybe try to print type (file) and type (string), as there is something fishy here - with an open file as an argument, I just can't reproduce your problem! (There are other errors in your code, but nobody can throw this exception.) Oh by the way, as a best practice, DO NOT use the names of built-in functions such as file
for your own purposes - this is causing an incredible amount of confusion!
a source to share