10.1 从文件中读取数据
10.1.1 读取整个文件
with open(~) as object:
contents=object.read()
with open('C:/Users/jou/Desktop/input.txt') as file_object:
contents=file_object.read()print(contents.rstrip())
10.1.2 文件路径
#文件路径读取方式1
filepath='C:/Users/jou/Desktop/input.txt'
#文件路径读取方式2
filepath=r'C:\Users\jou\Desktop\input.txt'
#文件路径读取方式3
filepath='C:\\Users\\jou\\Desktop\\input.txt'
10.1.3 逐行读取
filepath='C:/Users/jou/Desktop/input.txt'with open(filepath) as file_object:forline infile_object:#因为在这个文件中,每行的末尾都有一个看不见的换行符,而print 语句也会加上一个换行符,
#因此每行末尾都有两个换行符:一个来自文件,另一个来自print 语句。
#.rstrip() 消除空白行
print(line.rstrip())
10.1.4 创建一个包含文件各行内容的列表
filepath='C:/Users/jou/Desktop/input.txt'with open(filepath) as file_object:
lines=file_object.readlines()#打印列表
print(lines)#逐行打印列表元素
for line inlines:print(line.rstrip())
10.1.5 使用文件的内容
filepath='C:/Users/jou/Desktop/input.txt'with open(filepath) as file_object:
lines=file_object.readlines()
pi_string= ''
for line inlines:
pi_string+= line.strip() #.strip() 消除所有空格#打印列表各元素组成的字符串
print(pi_string)
10.1.6 包含一百万位的大型文件
#文件路径读取方式1
filepath=r'D:\h5.csv'
#创建一个包含文件各行内容的列表
with open(filepath) as file_object:
lines=file_object.readlines()for line inlines:print(line.rstrip())print(len(lines))
10.2 写入文件
10.2.1 写入空文件
#调用open() 时需要提供另一个实参,告诉Python你要写入打开的文件。#读取模式 ('r' )、写入模式 ('w' )、附加模式 ('a' )或让你能够读取和写入文件的模式('r+' )。#如果你省略了模式实参,Python将以默认的只读模式打开文件。#如果你要写入的文件不存在,函数open() 将自动创建它。
filepath='C:\\Users\\jou\\Desktop\\output.txt'with open(filepath,'w') as file_object:
file_object.write("I love programming.")
10.2.2 写入多行
#以写入('w' )模式打开文件时,如果指定的文件已经存在,Python将在返回文件对象前清空该文件。#函数write() 不会在你写入的文本末尾添加换行符#要让每个字符串都单独占一行,需要在write() 语句中包含换行符
filepath='C:\\Users\\jou\\Desktop\\output1.txt'with open(filepath,'w') as file_object:
file_object.write("I love programming.")
file_object.write("I love creating new games.")
filepath='C:\\Users\\jou\\Desktop\\output2.txt'with open(filepath,'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
10.2.3 附加到文件
filename='C:\\Users\\jou\\Desktop\\output.txt'
#如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式 打开文件。#你以附加模式打开文件时,Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。#如果指定的文件不存在,Python将为你创建一个空文件。
with open(filename, 'a') as file_object:
file_object.write("\nI also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
10.3 异常
Python使用被称为异常 的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知所措的错误时,它都会创建一个异常对象。
如果你编写了处理该异常的代码,程序将继续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。
异常是使用try-except 代码块处理的。try-except 代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。
使用了try-except 代码块时,即便出现异常,程序也将继续运行:显示你编写的友好的错误消息,而不是令用户迷惑的traceback。
10.3.1 处理ZeroDivisionError异常
division.py
print(5/0)
IndentationError: unexpected indent
print(5/0)
ZeroDivisionError: division by zero
print(5/0)
10.3.2 使用try-except代码块
try:print(5/0)exceptZeroDivisionError:print("You can't divide by zero!")
10.3.3 使用异常避免崩溃
10.3.4 else代码块
#通过将可能引发错误的代码放在try-except 代码块中,可提高这个程序抵御错误的能力。#错误是执行除法运算的代码行导致的,因此我们需要将它放到try-except 代码块中。#这个示例还包含一个else 代码块;依赖于try 代码块成功执行的代码都应放到else 代码块中
print("Give me two numbers, and I'll divide them.")print("Enter 'q' to quit.")whileTrue:
first_number= input("\nFirst number:")if first_number == 'q':breaksecond_number= input("Second number:")try:
answer= int(first_number) /int(second_number)exceptZeroDivisionError:print("You can't divide by 0!")##10.3.4 else 代码块
else:print(answer)
10.3.5 处理FileNotFoundError异常
filename = 'alice.txt'with open(filename) as f_obj:
contents=f_obj.read()
filename= 'alice.txt'
try:
with open(filename) as f_obj:
contents=f_obj.read()exceptFileNotFoundError:
msg= "Sorry, the file" + filename + "does not exist."
print(msg)
10.3.6 分析文本
filename = r"D:\h5.csv"
try:
with open(filename) as f_obj:
contents=f_obj.read()exceptFileNotFoundError:
msg= "Sorry, the file" + filename + "does not exist."
print(msg)else:#计算文件大致包含多少个单词
#方法split() 以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中
words =contents.split()
num_words=len(words)print("The file" + filename + "has about" + str(num_words) + "words.")
10.3.7 使用多个文件
#invalid syntax 该问题是语法错误,说明你的语句不合规则
defcount_words(filename):"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents=f_obj.read()exceptFileNotFoundError:
msg= "Sorry, the file" + filename + "does not exist."
print(msg)else:#计算文件大致包含多少个单词
words =contents.split()
num_words=len(words)print("The file" + filename + "has about" + str(num_words) + "words.")
filenames= [r"D:\h5.csv", r"D:\h6.csv", r"D:\h7.csv"]for filename infilenames:
count_words(filename)
10.3.8 失败时一声不吭
try:print(5/0)exceptZeroDivisionError:pass
10.4 存储数据
10.4.1 使用json.dump()和json.load()
importjson
numbers= [2, 3, 5, 7, 11, 13]
filename= 'numbers.json'
#使用json.dump() 来存储这组数字#函数json.dump() 接受两个实参:要存储的数据以及可用于存储数据的文件对象。#我们指定了要将该数字列表存储到其中的文件的名称。通常使用文件扩展名.json来指出文件存储的数据为JSON格式。#我们以写入模式打开这个文件,让json 能够将数据写入其中
with open(filename, 'w') as f_obj:#我们使用函数json.dump() 将数字列表存储到文件numbers.json中
json.dump(numbers, f_obj)#这次我们以读取方式打开这个文件
filename = 'numbers.json'
#使用函数json.load() 加载存储在numbers.json中的信息,并将其存储到变量numbers 中
with open(filename) as f_obj:
numbers=json.load(f_obj)print(numbers)
10.4.2 保存和读取用户生成的数据
importjson#如果以前存储了用户名,就加载它#否则,就提示用户输入用户名并存储它
filename = 'username.json'
try:
with open(filename) as f_obj:
username=json.load(f_obj)exceptFileNotFoundError:
username= input("What is 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 + "!")
10.4.3 重构
代码能够正确地运行,但可做进一步的改进——将代码划分为一系列完成具体工作的函数。这样的过程被称为重构 。
重构让代码更清晰、更易于理解、更容易扩展。
importjson#代码能够正确地运行,但可做进一步的改进—#将代码划分为一系列完成具体工作的函数。这样的过程被称为重构
defget_stored_username():"""如果存储了用户名,就获取它"""filename= 'username.json'
try:
with open(filename) as f_obj:
username=json.load(f_obj)exceptFileNotFoundError:returnNoneelse:returnusernamedefget_new_username():"""提示用户输入用户名"""username= input("What is your name?")
filename= 'username.json'with open(filename,'w') as f_obj:
json.dump(username, f_obj)returnusernamedefgreet_user():"""问候用户,并指出其名字"""username=get_stored_username()ifusername:print("Welcome back," + username + "!")else:
username=get_new_username()print("We'll remember you when you come back," + username + "!")
greet_user()