8 读写文件
8.3 用shelve
模块保存变量
利用shelve
模块,可以将python中的变量保存到二进制的shelf
文件中。若运行一个程序,并输入一些配置设置,可以将其保存在shelf
文件中,让程序下一次运行时加载它们。
import shelve
#1
shelffile = shelve.open('mydata')
cats = ['sjakdn','hjdb','nfkjd']
shelffile['cats'] = cats
shelffile['bats'] = cats
shelffile.close()
********************************1**********************************
调用函数shelve.open()并传入一个文件名,返回值保存在一个变量中。对变量的shelf
值进行修改,像一个字典一样,其中创建了2个键都保存了cats所对应的数组值。运行后生
成3个文件分别是mydata.bak、mydata.dat、mydata.dir,这些二进制文件包含了存储
在shelf中的数据。
*******************************************************************
#2
shelffile = shelve.open('mydata')
print(type(shelffile))#打印文件类型
print(shelffile['cats'])#打印键cats对应的值
shelffile.close()
********************************2**********************************
打开文件并打印其类型和键cats所包含的值,结果如下:
<class 'shelve.DbfilenameShelf'>
['sjakdn', 'hjdb', 'nfkjd']
*******************************************************************
#3
shelffile = shelve.open('mydata')
key_vlue = list(shelffile.keys())
print(key_vlue)
dat_vlue = list(shelffile.values())
print(dat_vlue)
shelffile.close()
********************************3**********************************
像字典一样,shelf值有keys()和values()方法,返回shelf中键和值的类似列表值。
因为返回的是类似列表值,不是真正的列表,所以应将它们传递给list()函数获得列表形式
结果如下:
['cats', 'bats']
[['sjakdn', 'hjdb', 'nfkjd'], ['sjakdn', 'hjdb', 'nfkjd']]
*******************************************************************
8.4 用pprint.pformat()
函数保存变量
此函数的调用需要导入import pprint
,可以用来保存需要保留的变量和他的内容,以便将来使用。pprint.pformat()
函数提供一个字符串,可以将它写入.py
文件,成为自己的模块,可以在需要的时候导入它。例程:将一个保存了字典数组的变量cats
和其内容保存在mycats.py
文件中。
import pprint
cats = [{'name':'zophie','desce':'chjsa'},{'name':'pooka','desc':'fluly'}]#创建一个字典数组
print(pprint.pformat(cats))#打印这个字典数组
fileobj = open('mycats.py','w')#以写模式打开一个文件
fileobj.write('cats = ' + pprint.pformat(cats) + '\n')#将字典数组的内容写入文件中
fileobj.close()#关闭文件
可以将以上保存文件的脚本文件导入程序之中使用如下:
import mycats
print(mycats.cats)
print(mycats.cats[0])#数组0的字典内容
print(mycats.cats[0]['name'])#数组0字典中键name对应的值
*************************输出如下**************************************
[{'desce': 'chjsa', 'name': 'zophie'}, {'desc': 'fluly', 'name': 'pooka'}]
{'desce': 'chjsa', 'name': 'zophie'}
zophie
**********************************************************************
random.shuffle()
函数随机打乱次序,random.randint(a,b)
函数输出一个随机数字。
>>>import random
>>> stst = ['hello','world','stay','banana']
>>> random.randint(1,10) #随机输出范围内的一个数字
5
>>> random.shuffle(stst) #随机排序
>>> print(stst) #输出
['hello', 'banana', 'stay', 'world']
>>> random.shuffle(stst)
>>> print(stst)
['world', 'hello', 'banana', 'stay']