Python编程:从入门到实践-文件和异常
-
1、从文件中读取数据
-
读取整个文件
1 >>> import this 2 The Zen of Python, by Tim Peters 3 4 Beautiful is better than ugly. 5 Explicit is better than implicit. 6 Simple is better than complex. 7 Complex is better than complicated. 8 Flat is better than nested. 9 Sparse is better than dense. 10 Readability counts. 11 Special cases aren't special enough to break the rules. 12 Although practicality beats purity. 13 Errors should never pass silently. 14 Unless explicitly silenced. 15 In the face of ambiguity, refuse the temptation to guess. 16 There should be one-- and preferably only one --obvious way to do it. 17 Although that way may not be obvious at first unless you're Dutch. 18 Now is better than never. 19 Although never is often better than *right* now. 20 If the implementation is hard to explain, it's a bad idea. 21 If the implementation is easy to explain, it may be a good idea. 22 Namespaces are one honking great idea -- let's do more of those! 23 >>> 24 >>>
#!/usr/bin/env python #-*- encoding:utf-8 -*- with open('Zen.txt') as file_object: contents = file_object.read() print(contents)
-
逐行读取
#!/usr/bin/env python #-*- encoding:utf-8 -*- filename = 'Zen.txt' with open(filename) as file_object: for line in file_object: print(line)
-
创建包含文件各行内容的列表
1 #!/usr/bin/env python 2 #-*- encoding:utf-8 -*- 3 filename = 'Zen.txt' 4 with open(filename) as file_object: 5 lines = file_object.readlines() 6 print(lines) 7 for line in lines: 8 print(line.rstrip())
方法readlines()从文件中读取每一行,存储在一个列表
-
2、写入文件
-
写入空文件
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 filename = 'programming.txt' 4 with open(filename, 'w') as file_object: 5 file_object.write("I love programming.")
open()提供两个实参,第一个实参是要打开的文件的名称,第二个实参('w'),以写入模式打开文件。打开文件,可指定读取模式('r'),写入模式('w'),附加模式('a') 或读取和写入(r+)。如果未指定模式实参,Python将以默认的只读模式打开文件。
在5行,使用文件对象的方法write()将一个字符串写入文件。
注意:Python只能将字符串写入文本文件,要将数值数据存储子啊文本文件,需要使用函数str()将其转化为字符串格式 。
-
写入多行
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 filename = 'programming.txt' 4 with open(filename, 'w') as file_object: 5 file_object.write("I love programming.\n") 6 file_object.write("I love creating new games.\n")
这里,需要使用\n换行符,还可以使用空格、制表符、空行来设置输出格式
-
附加到文件
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 filename = 'programming.txt' 4 with open(filename, 'a') as file_object: 5 file_object.write("I love programming.\n") 6 file_object.write("I love creating new games.\n")
-
3、异常
-
处理ZeroDivisionError异常
#!/usr/bin/env python #-*- encoding:utf-8 -*- try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!")
-
使用异常避免崩溃
#!/usr/bin/env python #-*- encoding:utf-8 -*- 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)
-
4、存储文件
-
使用json.dump()和json.load()
第一个程序将使用json.dump来存储数字,第二个程序将使用json.load()读取到内存
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 import json 4 numbers = [2, 3, 5, 7, 11, 13] 5 filename = 'numbers.json' 6 with open(filename, 'w') as f_obj: 7 json.dump(numbers, f_obj)
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 import json 4 filename = 'numbers.json' 5 with open(filename) as f_obj: 6 numbers = json.load(f_obj) 7 print(numbers)
-
保存和读取用户生成的数据
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 import json 4 username = input("What is your name ? ") 5 filename = 'username.json' 6 with open(username, 'a') as f_obj: 7 json.dump(username, f_obj) 8 print("We'll remember you when you come back, " + username + "!")
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 import json 4 filename = 'tiandi' 5 with open(filename) as f_obj: 6 username = json.load(f_obj) 7 print("Welcome back, " + username + "!")
使用json.load()将存储在username.json中的信息读取到变量username中。
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 import json 4 #如果以前存储了用户名,就加载它;否则提示用户输入用户名并存储它 5 filename = 'tianze.json' 6 try: 7 with open(filename) as f_obj: 8 username = json.load(f_obj) 9 except FileNotFoundError: 10 username = input("What is your name? ") 11 with open(filename,'w') as f_obj: 12 json.dump(username, f_obj) 13 print("We'll remember you when you come back, " + username + "!") 14 else: 15 print("Welcome back, " + username + "!")
-
重构
将代码划分为一系列完成具体工作的函数,这样的过程称为重构
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 #remember_me.py 4 import json 5 def greet_user(): 6 """问候用户,并指出其名字""" 7 filename = 'tiandi.json' 8 try: 9 with open(filename) as f_obj: 10 username = json.load(f_obj) 11 except FileNotFoundError: 12 username = input("What is your name? ") 13 with open(filename, 'w') as f_obj: 14 json.dump(username, f_obj) 15 print("We'll remember you when you come back, " + username + "!") 16 else: 17 print("Welcome back, " + username + "!") 18 greet_user()
函数 get_stored_username() 如果文件存储了用户名,函数获取并返回;如果文件tianxi.json不存在,这个函数就返回None
函数get_new_username() 将没有存储用户名时提示用户输入
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 #remember_me.py 4 import json 5 def get_stored_username(): 6 """如果存储了用户名,就获取它""" 7 filename = 'tianxi.json' 8 try: 9 with open(filename) as f_obj: 10 username = json.load(f_obj) 11 except FileNotFoundError: 12 return None 13 else: 14 return username 15 def get_new_username(): 16 """提示用户输入用户名""" 17 username = input("What is your name ? ") 18 filename = 'tianxi.json' 19 with open(filename, 'w') as f_obj: 20 json.dump(username, f_obj) 21 return username 22 def greet_user(): 23 """问候用户,并指出其名字""" 24 username = get_stored_username() 25 if username: 26 print("Welcome back, " + username + "!") 27 else: 28 username = get_new_username() 29 print("We'll remember you when you come back, " + username + "!") 30 greet_user()