01、从文件中读取数据
(1)读取整个文件
with open ('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)open()接收一个参数:要打开的文件的名称
Python在当前执行的文件所在的目录中查找指定的文件
read()函数读取这个文件的全部内容,作为一个字符串存储在contents中。
read()到达文件末尾时会返回一个空字符串,显示出来就是一个空行,可在print语句中使用rstrip()删除多出来的行。
(2)文件路径
Python打开不与程序文件位于同一个目录中的文件,需要提供文件路径,它让Python到系统的特定位置去寻找
A、相对文件路径
相对于当前运行的程序所在的目录,如:
with open(' python_work\filename.txt '):
B、绝对文件路径
将文件在计算机中的准确位置告诉Python
file_path = ' C:\Users\chunlian\Desktop\python_work\filename.txt '
with open( file_path ) as f_obj:
(3)逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
通过for循环来遍历文件中的每一行。
(4)用一个列表包含文件各行
如果想在with代码块外访问文件的各行,可以将文件的各行存储在一个列表中。
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
readlines()从文件中读取每一行,并将其存储在一个列表中。
(5)使用文件的内容,并去除空格和换行符
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
len()函数计算pi_string字符串包含多少个字符。
(6)读取大型文件的部分
filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string[ :52]+"......")
print(len(pi_string))
使用切片读取文件的一部分字符。
(7)检查某个字符串是否包含在文件中
filename = 'pi_million_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
birthday = input("Enter your birthday: ")
if birthday in pi_string:
print("yes")
else:
print("no")
02、写入文件
(1)写入空文件
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.")open()提供两个参数,第一个参数是要打开的文件的名称,第二个参数('w')告诉Python,我们要以写入模式打开这个文件。
读取模式('r'),写入模式('w'),附加模式('a'),读取和写入文件的模式('r+'),如果省略,则默认为只读模式。
如果要写入的文件不存在,函数open()会自动创建。如果指定文件已经存在,Python将先清空文件,在写入。
函数write()不会在写入的文本末尾添加换行符。
(2)添加换行符
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love China.\n")
file_object.write("I love programming\n")
(3)使用附加模式将字符串附加到文件中
使用附加模式('a'),Python不会在返回文件对象前清空文件,你写入文件的行都会添加到文件末尾。如果指定文件不存在,Python会创建一个空文件。
filename = 'programming.txt'
with open(filename,'a') as file_object:
file_object.write('I also love finding meaning.\n')
file_object.write("I love creating apps.\n")
03、异常
异常是使用try-except代码块处理的
(1)处理ZeroDivisionErroe异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
如果try代码块中的代码运行起来没有问题,pytho将跳过except代码块,如果try代码块中的代码运行导致了错误,就查找与这个错误对应的except代码块。运行其中代码。
(2)else代码块
将可能引发错误的代码放在try-except代码块中,依赖于try代码块成功执行的代码都应放在else代码块中。
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("\nSecond number:")
if second_number == 'q':
break
try:
answer = int(first_number)/int(second_number)
except:
print("You can't divide by 0!")
else:
print(answer)
即try代码块成功运行,才会运行else中的代码,否则运行except中的代码。
(3)处理FileNotFoundError异常
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry,the file "+filename+" does not exists!"
print(msg)
以为这个异常是函数open()导致的,所以放在try代码块内
(4)用split()方法分析文本中有多少个单词
filename = 'programming.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
print("The file "+filename+" not found!")
else:
words = contents.split()
num_words = len(words)
print("The file "+filename+ " has "+str(num_words)+" words")
split()方法以空格为分隔符,将字符串拆分成多个部分,并将这些部分存储到一个列表中。结果是一个包含字符串中所有单词的列表。
(5)使用列表处理多个文件
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
print("The file "+filename+" not found!")
else:
words = contents.split()
num_words = len(words)
print("The file has "+str(num_words)+" words!")
filenames = ['guest.txt','alice.txt','guest_book.txt','programming.txt']
for filename in filenames:
count_words(filename)
(6)出现错误时不报错
在except中使用pass使得运行excep语句时什么也不输出
filenames = ['cats.txt','dogs.txt','alice.txt']
for filename in filenames:
try:
with open(filename) as f_obj:
content = f_obj.read()
except FileNotFoundError:
pass
else:
print(content)
04、存储数据
模块json可以将Python数据转储到文件中,并在程序再次运行时加载该文件中的数据。
(1)使用json.dump( )
import json
numbers = [1,2,3,4,5,6]
filename = 'number.json'
with open(filename,'w') as f_obj:
json.dump(number,f_obj)使用json.dump( )来存储数据
json.dump( )接受两个参数:要存储的数据,以及用于存储数据的文件对象。
需要导入json模块
文件扩展名使用 .json
(2)使用json.load( )
import json
filename = 'number.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
json.load( )加载存储在number.json中的信息
(3)使用json保存和读取用户生成的数据。
A、保存用户姓名
import json
username = input("What is your name?")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remember you when you come back,"+username)
B、从json文件中显示姓名
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back,"+username+"!")
C、将上述两个代码合并,第一次运行和第二次运行输出会有点不一样。
import json
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
with open(filename,'w') as f_obj:
username = input("Enter your name:")
json.dump(username,f_obj)
print("We'll remember you "+username+".")
else:
print("Welcome back," +username+".")
(4)重构
将代码划分为一系列完成具体工作的函数,称为重构。
import json
def get_stored_username():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
username = get_stored_username()
if username:
print("Welcome back "+username+"!")
else:
username = input("What is your name?")
filename = 'username.json'
with open(filename) as f_obj:
json.dump(username,f_obj)
print("We'll remember you "+username)
greet_user()