#*********************** 文件内容转换 **********************
#json字符串 ——> 字典dict
jsonDict = json.loads(jsonString)
#字典dict ——> json字符串
jsonString = json.dumps(jsonDict)
#字段循环
user = {'name':'Tom', 'age':'18',}
for i in user:#循环效率高
print(i) #输出name,age
for k,v in user.items():#循环效率低
print(k,v) #输出name Tom; age 18
#*********************** 文件读写 **********************
1、读取文件
fp = open('log1.txt', "r", encoding='utf-8')
fp.read(5)#读取5个字符,不加数值则读取全部数据
fp.close()
#高效率读取逐行文件
fp = open(stnFile,'r', encoding='utf-8')
for i in fp:
print(i)
fp.close()
2、写入文件
fp = open('log1.txt', "w", encoding='utf-8')#文件存在则清空,不存在则创建
fp.write('This is China')#写入字符
fp.close()
fp = open('log1.txt', "a", encoding='utf-8')#文件追加写
fp.truncate(5)#光标跳转到第5个字符处,5个字符后的所有内容均清除
fp.close()
3、文件读取模式
'r': open for reading (default)
'w': open for writing, truncating the file first
'x': create a new file and open it for writing
'a': open for writing, appending to the end of the file if it exists
'b': binary mode
't': text mode (default)
'+': open a disk file for updating (reading and writing)
'U': universal newline mode (deprecated)
'r+':文件正常读取,但是写只能写最后面
'w+':文件清空写入,读取时需要跳转光标位置
4、逐行读取文件
fp = open('log1.txt', "r", encoding='utf-8')
lineString = fp.readline()#读取一行数据
for line in fp :
print(line)
linesString = fp.readlines()#读取所有行数据
fp.close()
5、光标跳转
fp.tell()#返回光标所在文件中的位置
fp.seek(0)#光标跳转到文件开头位置
fp.flush()#刷新缓存区,直接输出
6、with操作读写文件,不必关闭文件,可同时操作两个文件
with open('log1.txt', "r") as fp1, open('log2.txt', "w") as fp2:
for line in fp1:
line=''.join([line.strip(), 'end 3'])
fp2.write(line)
#*********************** Json文件读写 **********************
#json模块和pickle模块操作json对象是一样的方法,pickle还能读写函数类等对象
result = {}
with open(srcFile, "r", encoding='gbk') as fp:#参数encoding是文件的编码
fileJson = json.loads(fp.read())#先读取fp文件数据,在转为json对象
fileJson = json.load(fp)#直接读取fp文件内的json对象
for obj in fileJson :
result.append(obj)
with open(dstFile, "w", encoding='utf8') as fp:
fp.write(json.dumps(result))#先json对象转为字符串,在写入文件
json.dump(result, fp)#直接写入fp文件内的json对象
#*********************** Json文件中文防止乱码 **********************
with open(dstFile, "w", encoding='utf-8') as fp:
json.dump(result, fp, ensure_ascii=False)
str_data = json.dumps(data,ensure_ascii=False)#防止字典中的中文乱码
import json # 需要导入JSON包
data = {'name': '张三', "male": True, "money": None} # 字典格式
str_data = json.dumps(data) # 序列化,转化为合法的JSON文本(方便HTTP传输)
print(str_data)
#*********************** shelve模块 **********************
#1、shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;
#2、key必须为字符串,而值可以是python所支持的数据类型,记录文件会生成.bak/.dat/.dir三个文件,不可查看;
#3、写入shelve文件数据
import shelve
f = shelve.open(r'shelve.txt')#打开文件后返回shelve对象
f['info']={'name':'alex','age':'18'}#打开后直接操作数据
f.close()
#4、读取shelve文件数据
import shelve
f = shelve.open(r'shelve.txt')#打开文件后返回shelve对象
print(f.get('info'))#若info已经存储,则打开文件后可直接索引
f.close()