Reputation: 61
I'm having trouble with my code which is producing the wrong output.
def main():
count = 1
filename = input('Enter filename: ')
for lines in open(filename):
lines.strip('')
print('Total # of characters: ',len(lines))
count = count + 1
print('Total number of lines =', count)
main()
The problem - Write a program that reads a file, words.txt, that has one word per line and prints out the total number of characters and the total number of lines in the file.
So, my code using count to count the number of lines in the file which will be printed at the end. This count works fine. However, counting the characters is wrong. My output...
Enter filename: word.txtEnter filename: word.txt
Total # of characters: 3
Total # of characters: 6
Total # of characters: 5
Total # of characters: 6
Total # of characters: 6
Total number of lines = 5
The word.txt file =
hi
hello
hiiiiiiii
herrooo
herr
Upvotes: 2
Views: 469
Reputation: 50600
The problem you have is with the lines.strip('')
line. By passing it a parameter, it will only strip the line when it is ''
. The other problem is that you are not assigning this statement to anything. Try replacing it with
lines = lines.strip()
Upvotes: 1