(一)从文件中读取数据
1、读取文本文件,并打印出来
#读取txt文件,并换行
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
输出的末尾末尾多了一个空行,因为 read() 到达文件末尾时返回一个空字符串,这个空字符串显示出来时就是一个空行。要删除多余的空行,可在print语句中使用rstrip(),改写为:
print(contents.rstrip())
2、文件路径
如果文本文件在python的py文件夹下,访问并打开文本需要的语句为:
with open('pi_digits.txt') as file_object:
如果文本文件在py文件所在位置的 子文件夹 text_files 中,则访问当时可以改写为:
with open('text_files \ pi_digits.txt') as file_object:
如果不是上述情况,可以采用绝对文件路径的方式:
file_path = 'D:\users\my\python\files\text_files\pi_digits.txt'
with open(file_path) as files_object:
3、逐行读取
#逐行读取文件
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line) # 这种方式打印出来的文本在每行后边多了一行空白,
# 因为,在每行的末尾都有一个看不见的换行符,而print语句也会加上一个换行符,
# 导致打印出来的末尾有2个换行符,一个来自文件,另外一个来自print语句
#逐行读取文件,删除空白行
filename = 'pi_digits.txt'
print("\n")
with open(filename) as file_object:
for line in file_object:
print(line.rstrip()) # 这种方式打印出来的文本在每行后边多了一行空白,
4、创建一个包含文件各行内容的列表,并使用文件内容
使用关键字with时,open()返回的文件对象只在with代码块内可用。如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表:你可以立即处理文件的各个部分,也可推迟到程序后面再处理。
# 内容创建为列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
将文件读取到内存中后,就可以以任何方式使用这些数据了。
# 内容创建为列表,并使用
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
此时,打印出来的一串 pi 数字中有空格,因此程序可以改写为:
# 内容创建为列表,bigshiyong
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
读取文本文件时,Python将其中的所有文本都解读为字符串。如果你读取的是数字,并要将其作为数值使用,就必须使用函数int()将其转换为整数,或使用函数float()将其转换为浮点数。
只要内存够大,python可以处理很大的文本数据,下面判断自己的生日是否在pi中,代码如下:
filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
birthday = input("Enter your birthday, in the form mmddyy.\n")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pil!")
else:
print("Your birthday does not appear in the first million figits of pi.")
(二)写入文件
1、写入空文件
open()时提供了两个实参。第一个实参是要打开的文件的名称;第二个实参('w')告诉Python,我们要以写入模式打开。可指定读取模式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')。如省略了模式实参,Python将默认只读。
如果你要写入的文件不存在,函数open()将自动创建它。以写入('w')模式打开文件时,如果指定的文件已存在,Python将在返回文件对象前清空该文件。
#文件中写信息
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
file_object.write("I love creating new games.")
file_object.write("I also love finding meaning in large datasets.")
file_object.write("I love creating apps that can run in a browser.")
2、附加文件
如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件。你以附加模式打开文件时,Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。
如果指定的文件不存在,Python将为你创建一个空文件。
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")
(三)异常
1、处理ZeroDivisionError 异常
Python使用被称为异常的特殊对象来管理程序执行期间发生的错误。每发生错误时,它都会创建一个异常对象。若编写了处理该异常的代码,程序将继续运行;若未对异常进行处理,程序停止并显示一个traceback,包含有关异常的报告。异常处理要用:try-except代码块。
#被除数为0的错误处理
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
完成一个鉴定单的除法运算:
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
answer = int(first_number) / int(second_number)
print(answer)
上述程序中,如果出现除数为0,则会报错,导致程序无法运行。鉴于此应该把运算放入try--except 模块中。
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: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You cant divide by 0!")
else:
print(answer)
2、处理FileNotFoundError 异常
如果要打开文件中不存在的txt文本文件,会报错。这个错误是函数open()导致的,因此要处理这个错误,必须将try语句放在包含open()的代码行之前。
# 处理文件读取错误
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + "does not exist."
print(msg)
3、分析文本
split()以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。
# 处理文件读取错误
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
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.")
处理多个文件,可以将单词数量计算定义为一个函数,进行调用。程序如下:
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
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 = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
4、发生错误时保持沉默
当程序发生错误时,我们可以让程序什么都不做,即忽略错误,然后继续往下执行。此时就可以用pass语句。
try:
--snip--
except FileNotFounError:
pass
else:
--snip--
(四)存储数据
模块 json 能将简单的Python数据结构转储到文件中,并在程序再次运行时加载文件中数据。还可以使用 json 在Python程序间分享数据。JSON数据格式并非Python专用,属于一种轻便格式,故此可 以 JSON 格式存储的数据与使用其他编程语言的人分享。
JSON(JavaScript Object Notation)格式最初是为JavaScript开发的,但随后成了一种常见的格式,被包括Python在内的众多语言采用。
1、数据存储和读取
利用 json 实现数据的存储和读取,一个小小的实例如下:
import json
number =[2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(number,f_obj) #用函数json.dump()将数字列表存储到文件numbers.json中
with open(filename) as f_obj:
num_read = json.load(f_obj) #用函数json.load()将数据文件中的数值读出来
print(num_read)
加入异常处理的文件保存和读取
import json
#如果以前存储了用户名就加载他,否则提示用户输入用户名并存储
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name?")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We will remember you when you caome back, " + username + "!")
else:
print("Welcome back, " + username + "!")
2、重构
你经常会遇到这样的情况:代码能够正确地运行,但可做进一步的改进——将代码划分为一系列完成具体工作的函数。这样的过程被称为重构。重构让代码更清晰、更易于理解、更容易扩展。
将上述程序实现的功能进行模块化,每个功能用一个新的函数定义,这样方便后续增加功能和用户
def get_sorted_username:
"""如果存储了客户信息,就获取它"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""提示用户输入新的用户名"""
username = input("What is your name?\n")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username,f_obj)ch
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()