steve
steve

Reputation: 61

Openfile function in python

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

Answers (2)

Andy
Andy

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

karthikr
karthikr

Reputation: 99660

By doing lines.strip('') you are stripping only on ''

Do this:

lines = lines.strip()

strip() would strip out the \n at the end too.

Upvotes: 3

Related Questions