我的代码产生错误的输出时遇到问题。
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()
问题 - 编写一个程序来读取一个文件,单词.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
单词.txt文件 =
hi
hello
hiiiiiiii
herrooo
herr
通过执行lines.strip('')
,您只会在''
剥离
这样做:
lines = lines.strip()
strip()
最后也会去掉n
。
您遇到的问题出在lines.strip('')
行上。通过向它传递一个参数,它只会在''
时剥离该行。另一个问题是你没有将此语句分配给任何东西。尝试将其替换为
lines = lines.strip()