Traceback (most recent call last):
File "alice.py", line 3,in<module>withopen(filename)as f_obj:
FileNotFoundError:[Errno 2] No such fileor directory:'alice.txt'
filename ='alice.txt'try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ="Sorry, the file "+ filename +" does not exist."print(msg)
分析文本
>>> title ="Alice in Wonderland">>>> title.split()>['Alice','in','Wonderland']
filename ='alice.txt'try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError
: msg ="Sorry, the file "+ filename +" does not exist."print(msg)else:# 计算文件大致包含多少个单词
words = contents.split()
num_words =len(words)print("The file "+ filename +" has about "+str(num_words)+" words.")
使用多个文件
defcount_words(filename):"""计算一个文件大致包含多少个单词"""try:withopen(filename)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ="Sorry, the file "+ filename +" does not exist."print(msg)else:# 计算文件大致包含多少个单词
words = contents.split()
num_words =len(words)print("The file "+ filename +" has about "+str(num_words)+" words.")
filename ='alice.txt'
count_words(filename)
defcount_words(filename):--snip
filenames =['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']for filename in filenames:
count_words(filename)
The file alice.txt has about 29461 words.
Sorry, the file siddhartha.txt does not exist.
The file moby_dick.txt has about 215136 words.
The file little_women.txt has about 189079 words.
失败时一声不吭
defcount_words(filename):"""计算一个文件大致包含多少个单词"""try:--snip-except FileNotFoundError:passelse:--snip-
filenames =['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']for filename in filenames:
count_words(filename)
The file alice.txt has about 29461 words.
The file moby_dick.txt has about 215136 words.
The file little_women.txt has about 189079 words.