1、从文件中读取数据
- 读取整个文件
#关键字with在不需要访问文件后自动将其关闭
#open('pi_digits.txt')返回一个表示文件pi_digits.txt的对象,并将该对象存储在变量file_object中
#file_object.read()读取该文件对象对应文件的全部内容
#contents.rstrip(),由于read()读取到文件末尾时返回一个空字符串,rstrip()用于删除该空字符串
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
- 逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
- 创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
#由于在with中返回的文件对象只在with代码块中可用
#如果要在with代码块外访问文件的内容,可将文件每行存储在列表中
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
2、写入文件
- 写入空文件
filename = 'programming.txt'
#以写入模式'W'打开文件,如果文件不存在,则创建该文件,若已存在则清空文件内容
with open(filename, 'w') as file_object:
file_object.write("I love you.")
- 在文件末尾写入
#以附加模式'a'打开文件,能够在文件末尾写入文件
with open(filename, 'a') as file_object:
file_object.write("I love you.\n")
file_object.write("What about you?\n")
3、异常
- 使用try-except代码块来处理可能引发的异常
- 将可能引发异常的代码放在try代码块中
- 将异常处理的代码放在except代码块中
try:
print(9/0)
except ZeroDivisionError:
print("You can't divide by zero!")
- 将依赖于try代码块成功执行的代码放到else代码块中
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
second_number = input("\nSecond number: ")
if first_number == 'q' or second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
- 处理FileNotFoundError异常
def count_words(filename):
'''计算一个文件大概有多少个单词'''
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
# msg = "Sorry, the file " + filename + " does not exist."
# print(msg)
pass
else:
#计算文件中包含多少个单词
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
#计算文件中包含多少个'you'
you_count = words.count('you')
print("'you': " + str(you_count))
filename = 'alice.txt'
count_words(filename)
4、使用json存储数据
- 使用json.dump()来存储数字列表
import json
numbers = [ 2, 3, 5, 7, 11, 13 ]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
- 使用json.load()来读取列表到内存中
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
-练习
import json
#如果以前存储了用户名,就加载它
#否则,就提示用户输入用户名存储它
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What's your name? ")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")