Python学习——文件操作和异常处理

Posted qilf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习——文件操作和异常处理相关的知识,希望对你有一定的参考价值。


# title = "Alice in Wonderland"
# print(title.split())


def count_words(filename):
‘‘‘ count how many words in a text file ‘‘‘
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
#msg = "Sorry, the file " + filename + " does not exist."
#print(msg)
else:
words = contents.split()
print("The file " + filename + " has about " + str(len(words)) + " words.")


def addTwoNumber():
‘‘‘ add two numbers. ‘‘‘
first_number = input("First Number: ")
second_number = input("Second Number: ")
try:
first_number = int(first_number)
second_number = int(second_number)
except ValueError:
print("Please check if your input is legal.")
return False
else:
res = first_number + second_number
print(str(first_number)+" + "+str(second_number)+" is "+str(res))
return True
































以上是关于Python学习——文件操作和异常处理的主要内容,如果未能解决你的问题,请参考以下文章

python文件操作和异常处理

Head First Python 学习笔记-Chapter3:文件读取和异常处理

python之文件操作及异常处理

python之文件操作及异常处理

python学习_异常和抛出

python 3操作文件的异常处理