刚看完白夜行,想看看究竟有多少字,正好看到书里有异常处理的作业,就顺便一起写了。
file_name = '東野圭吾-白夜行.txt'
try:
with open(file_name, encoding='utf8') as file_obj:
#由于书名不是英文,要加上 encoding='utf8'
contents = file_obj.read()
except FileNotFoundError:
msg = 'Sorry, the file' + file_name + ' does not exist.'
print(msg)
else:
words = contents.rstrip()
num_words = len(words)
print('The file ' + file_name + ' has about ' + str(num_words) + ' words.')
结果:
The file 東野圭吾-白夜行.txt has about 487761 words.
哇,我真是太不容易了,看的都快吐了好么。。。