2

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
2
  • What is the actual issue you are having? That output looks correct to me, considering the newline characters. Commented Oct 14, 2013 at 19:35
  • The problem is the length of the characters. For instance, the length of hi should be 2. How would I get rid of the new line character? Commented Oct 14, 2013 at 19:37

2 Answers 2

3

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

Do this:

lines = lines.strip()

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

Sign up to request clarification or add additional context in comments.

6 Comments

it should be lines= lines.strip(), not just lines.strip()
I didn't see your edit before my submission. +1 to you for the ninja edit
Also to just get rid of the newline, lines.rstrip('\n') would be more appropriate. Depending on whether a space is a valid "character" for the OP's purposes.
@karthikr Haven't seen ya in a long time. Where have you been? :)
@GamesBrainiac Here i am :)
|
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.