#!/usr/bin/env python
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as file_object:
contents=file_object.read()
except FileNotFoundError:
message="Sorry,the file "+filename+" does not exist."
print(message)
else:
#计算文件大致包含多少个单词
words=contents.split()
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
filenames=['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
其中siddhartha.txt不在文件夹内,想请问一下这是什么情况~
函数也需要缩进,按下面这段试下:
#!/usr/bin/env python
-*- coding: utf-8 -*-
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as file_object:
contents=file_object.read()
except FileNotFoundError:
message="Sorry,the file "+filename+" does not exist."
print(message)
else:
#计算文件大致包含多少个单词
words=contents.split()
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
filenames=['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
哥们,python要求严格的冒号过行后要留一个tab缩进,另外不知道你下面的else哪来的,给的注释掉了,以后这种error多查google
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as file_object:
contents=file_object.read()
except FileNotFoundError:
message="Sorry,the file "+filename+" does not exist."
print(message)
#else:
#计算文件大致包含多少个单词
words=contents.split()
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
filenames=['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
try后面的语句都没有进行缩进呢
如楼上所说,Python是用缩进控制代码的,你按下面这段试下?
#!/usr/bin/env python
-*- coding: utf-8 -*-
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as file_object:
contents=file_object.read()
except FileNotFoundError:
message="Sorry,the file "+filename+" does not exist."
print(message)
else:
#计算文件大致包含多少个单词
words=contents.split()
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
filenames=['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
另一种获取异常信息的途径是通过sys模块中的exc_info()函数。该函数回返回一个三元组:(异常类,异常类的实例,跟中记录对象)
可能是您的缩进有问题,在现在看来您的缩进是有问题的。你注意缩进规则。