P10-文件和异常
filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
open() 接受的参数是当前目录下的文件名返回一个文件对象 然后用AS赋值给 file_object使用
关键字with 在不需要访问文件后将其关闭 这里没有调用close()方法,因为过早或者过晚的关闭都会出问题,
这里使用with可以让Python自己去判断什么时候去关闭而不需要我们去操作
使用read()获取文件内容或者readlines()获取每一行的内容
filename = 'programming.txt' with open(filename, 'a') as file_object: file_object.write("I also love finding meaning in large datasets.\n") file_object.write("I love creating apps that can run in a browser.\n")
r只读模式 w写入模式 a附加模式 r+读写模式 如果不加就按照默认的只读模式
print("Give me two numbers, and I'll divide them.") print("Enter 'q' to quit.") while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("Second number: ") if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by 0!") else: print(answer)
print("Give me two numbers, and I'll divide them.") print("Enter 'q' to quit.") while True: first_number = input("\nFirst number: ") if first_number == 'q': break second_number = input("Second number: ") if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by 0!") else: print(answer)
异常处理
try
except
else
pass 在except中 写 pass代表什么都不做的意思,但是提示后面的人可能做些什么