python进阶-读写文件

使用python读写文件

 

前面部分是介绍json和 dict的相互转换;

然后介绍了读一个Json文本文件(文件有n行,整个文件是一个json字符串);

再后面介绍了读取文本文本,文件每一行是一个json字符串;

还介绍了如何写入json数据;

如何写入文本;如何追加写入;

附带了相关参考链接地址。

 

这个参考网站写的非常好:

 https://pythonexamples.org/python-read-json-file/


#!/usr/bin/python
# -*-coding:utf-8-*-

import sys
import os
import json



#--------------------------------------------

# dict 转为 json.  内置 str() 方法
# list,arr 转为字符串,内置 str() 方法
dicta = {"name": "henry", "age": 32}
lista = ["aa", "bb", "cc", "dd"]
listb = [1, 2, 3, 4, 5, 6, 7, 100, 200, 30, 40]

# str()内置方法,将 dict 转为json字符串
a1 = str(dicta)
# str() 内置方法,将 list 转为字符串
a2 = str(lista)
a3 = str(listb)
#witeFileObje = open("dict2str.txt",'w')
#witeFileObje.writelines(a1+"\n")
#witeFileObje.writelines(a2+"\n")
#witeFileObje.writelines(a3+"\n")
#witeFileObje.close()


#--------------------------------------------

# dict 转为 json , json.dumps() 方法
dicta = {"name": "henry", "age": 32}
jsonStr = json.dumps(dicta)


#--------------------------------------------
## https://pythonexamples.org/python-json-to-dict/

# json 字符串转为 dict类型,json.loads() 方法
import json

jsonString = '{"a":54, "b": 28}'
aDict = json.loads(jsonString)
print(aDict)
print(aDict['a'])
print(aDict['b'])

#--------------------------------------------

# json 字符串转为 dict类型,json.loads() 方法

import json

jsonString = '{"a":54, "b": {"c":87}}'
aDict = json.loads(jsonString)
print(aDict)
print(aDict['a'])
print(aDict['b'])
print(aDict['b']['c'])

#--------------------------------------------
# json array 转为 array
import json

jsonStr = '[{"a":1, "b":2}, {"c":3, "d":4}]'
aList = json.loads(jsonStr)
print(aList[0]['b'])


#======================
# 总结:
# json.dumps(dict), 将dict转为 jsonstr
# json.loads(jsonstr),将jsonstr 转为 dict




#--------------------------------------------
## https://pythonexamples.org/python-read-json-file/

# 读取 json 文件
import json

fileObject = open("data1.json", "r")
jsonContent = fileObject.read()
aList = json.loads(jsonContent)
print(aList)
print(aList['a'])
print(aList['b'])
print(aList['c'])

# 读取文件
fileObject2 = open("data1.json", "r")
new_dict = json.load(fileObject2)
print(new_dict)

# 读取json格式文件.读取的整个文件
pathfile1 = "./test.json"
if os.path.exists(pathfile1):
    if sys.version_info.major > 2:
        readFileObj = open(pathfile1, 'r', encoding = 'utf-8')
    else:
        readFileObj = open(pathfile1, 'r')
    ###读取一整个文件,文件里面可以有换行,只要是一个合法的json都可以
    dict_data = json.load(readFileObj)
    print(dict_data)


# 读取多行
print("-------------start11")
for line in open("testlines.json"):
    dict1 = json.loads(line)
    print(line)
print("-------------end11")


# 读取多行
file_obj = open("testlines.json")
all_lines = file_obj.readlines()
print("-------------start22")
for line in all_lines:
    print(line)
file_obj.close()
print("-------------end22")


# 读取json格式文件.一行一行读取
pathfile1 = "./testfile1.json"
if os.path.exists(pathfile1):
    if sys.version_info.major > 2:
        readFileObj = open(pathfile1, 'r', encoding = 'utf-8')
    else:
        readFileObj = open(pathfile1, 'r')

    line = readFileObj.readline()
    while line:
        dict_data = json.loads(line)
        print(dict_data)


#--------------------------------------------
# 读取 json 文件2

import json

fileObject = open("data2.json", "r")
jsonContent = fileObject.read()
aList = json.loads(jsonContent)
print(aList[0])
print(aList[0]['c'])



#--------------------------------------------
# 写入 json 文件1

import json

aDict = {"a":54, "b":87}
jsonString = json.dumps(aDict)
jsonFile = open("data.json", "w")
jsonFile.write(jsonString)
jsonFile.close()


#--------------------------------------------
# 写入 json 文件2
import json

aList = [{"a":54, "b":87}, {"c":81, "d":63}, {"e":17, "f":39}]
jsonString = json.dumps(aList)
jsonFile = open("data.json", "w")
jsonFile.write(jsonString)
jsonFile.close()




#--------------------------------------------
# 写入 json 文件3

# dict按照json格式写入文件
dict3 = { 'Apple': 4,
          'Banana': 2,
          'Orange': 6,
          'Grapes': 11}
wf = open("wt1.json","w")
json.dump(dict3,wf)
wf.close()

## 写入文件
# 写之前,先检验文件是否存在,存在就删掉
if os.path.exists("dest.txt"):
    os.remove("dest.txt")
mylist = ["luoluo", "taotao", "mumu"]

# 以写的方式打开文件,如果文件不存在,就会自动创建
file_write_obj = open("dest.txt", 'w')
for var in mylist:
    file_write_obj.writelines(var)
    file_write_obj.write('\n')
file_write_obj.close()



#---------------
# https://blog.csdn.net/wowocpp/article/details/79701704
# 追加写入文件 "a+"

import datetime

def writeMsg(fileName, strMsg:str):
    currentDateAndTime = datetime.datetime.now()
    strDate = currentDateAndTime.strftime("%Y-%m-%d")

    try:
        writeFileObj = open(fileName+strDate+".log","a+")
        currentDateTimeStr = currentDateAndTime.strftime("%Y-%m-%d %H:%M:%S")
        writeFileObj.write(currentDateTimeStr + "|" + strMsg+"\n")
    except Exception as ex:
        writeErrObj = open("error"+strDate+".log","a+")
        writeErrObj.write(f"some thing wrong with write {fileName} file .exception:{ex}")
        writeErrObj.close()
    finally:
        writeFileObj.close()







## 读取一整个json文件
bond_readFileObj:typing.IO = open("bond.txt","r")
bond_jsonContent = bond_readFileObj.read()
bond_dict = json.loads(bond_jsonContent)
# 'SZ'
SZ_str_end = 'SZ'
sz_list=[]
for value in bond_dict[SZ_str_end]:
    sz_list.append(value + "." + SZ_str_end)

# 'SH'
SH_str_end = 'SH'
sh_list=[]
for value in bond_dict[SH_str_end]:
    sh_list.append(value + "." + SH_str_end)

bond_list = []
for key in bond_dict:
    print("key:",key,",len:",len(bond_dict[key]))
    for value in bond_dict[key]:
        bond_list.append(str(value) + "." + key)


## 一行一行读取json
params_readFileObj = open("SEC_COM_MAIN_HOLDER_TEN_preload.log","r")
all_lines = params_readFileObj.readlines()
for line in all_lines:
    dict_one_line = json.loads(line)
    print(line)
params_readFileObj.close()


## 廖雪峰python
## https://www.liaoxuefeng.com/wiki/1016959663602400/1017607179232640

 

posted @ 2023-06-27 09:37  He_LiangLiang  阅读(16)  评论(0编辑  收藏  举报