I am currently trying to count the characters per line and the first 1,000 characters of a txt file. My code counts the characters of the file and produces no error, but does not stop the count at 1,000. I know there needs to be a break to fix this problem, but I do not know what I'm doing wrong. This is my first post and would like to apologize in advance if I'm not being succinct or clear enough.
This keeps the values of characters at over 1,000 but does not print them:
with open('myfile', 'r') as f:
characters = 0
for lines in f.readlines():
length = len(lines) - lines.count('\n')
characters += sum(len(length) for length in lines)
if characters >= 1000:
break
print('the number of characters in this line is: %s' % length)
print('the total number of characters is: %s' % characters)
and this also keeps the values of characters at over 1,000 and prints them:
with open('myfile', 'r') as f:
characters = 0
for lines in f.readlines():
length = len(lines) - lines.count('\n')
characters += sum(len(length) for length in lines)
print('the number of characters in this line is: %s' % length)
print('the total number of characters is: %s' % characters)