For my python class I was instructed to create a function that will read a file and report the number of lines, words, and characters. I can get the code to work, but once I try to convert it to a function, it doesn't work. what's wrong? I also need to return the values in a tuple. I keep getting this error:UnboundLocalError: local variable 'line_cnt' referenced before assignment
def file_elem(filenm):
f = open(filenm,'r')
wrd_cnt = 0
char_cnt = 0
line_len = 0
while f is open:
line_cnt = len(f.readlines( ))
for line in f:
f_lines = line.split()
wrd_cnt += len(f_lines)
no_spaces = ''.join(line.split())
char_cnt += len(no_spaces)
return print(line_cnt, wrd_cnt, char_cnt)
import os
x = os.path.join("C:", "\\temp", "practice4.txt")
file_elem(x)
print. You probably want to drop theprintfrom the return line, and print the result outside the function.while f is openlooks very suspicious to me... (you are checking whetherfand the global functionopenare the same object).while f is openis now my new favourite bit of English which is syntactically valid Python but doesn't do at all what a beginner would expect..while f is openshould be a new PEP recommendation! Seems more natural thanwith open("file") as f!