python中的Openfile函数

时间:2013-10-14 19:33:04

标签: python

我的代码出错了,导致输出错误。

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

问题 - 编写一个程序来读取一个文件,words.txt,每行有一个单词,并打印出文件中的总字符数和总行数。

所以,我的代码使用count来计算文件中最后打印的行数。这个计数工作正常。但是,计算字符是错误的。我的输出......

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

word.txt文件=

hi
hello
hiiiiiiii
herrooo
herr

2 个答案:

答案 0 :(得分:3)

通过执行lines.strip(''),您只能在''

上进行剥离

这样做:

lines = lines.strip()

strip()也会在最后删除\n

答案 1 :(得分:1)

问题在于lines.strip('')行。通过传递一个参数,它只会在''时删除该行。另一个问题是您没有将此语句分配给任何内容。尝试用

替换它
lines = lines.strip()
相关问题