python文件读写操作

1.json文件

   1.1 json文件读取

         1) 读取含有多行的json文件

import json # 由于文件中有多行,直接读取会出现错误,因此一行一行读取 #例如: #{"a":1} #{"b":2} #{"c":3}

file = open("writingReport.json", 'r', encoding='utf-8')

data_list = []

for line in file.readlines():

    dic = json.loads(line)

    data_list.append(dic)

    2) 读取含有单行的json文件

        方式1:使用python函数读取

        #文件内容例如[{"a",1},{"b",2},{"c",3}]

f=open("文件名.json","r",encoding="utf8")
a=eval("".join(f.readlines()))

       方式2:使用json包读取

import json
file = open(打开的文件名, encoding="utf8")
file_data = json.loads(file.read())
file.close()

    1.2 json文件写入

使用json第三方包读取

import json

with open(新建的json文件名.json, "w+", encoding="utf8") as f:
    f.write(json.dumps(数据,  indent=4, ensure_ascii=False))   #indent 控制显示格式,ensure_ascii用户控制在写入的文件中能显示中文

2.excel文件

    2.1 excel文件读取

    使用pandas读取excel文件

import pandas

df = pd.read_excel(filepath, sheet_name='sheet1') #读取excel文件,默认第一行为字段名

读取多个目录读取文件并在原基础增加信息写入到新文件中:

#文件目录结构
#一级目录。      读取的文件目录
  #二级目录
    #excel文件(包括多个sheet)
  #二级目录
    #excel文件(包括多个sheet)


import os
def create_dir_not_exist(path):
    if not os.path.exists(path):
        os.mkdir(path)
if __name__=="__main__":
    first_dir_str="读取的文件目录"
    new_first_dir_str="new"+first_dir_str
    create_dir_not_exist("new"+first_dir_str)
    sub_dirs_list=os.listdir(first_dir_str)
    for a_sub_dirs in sub_dirs_list:                        #遍历一级目录的所有文件
        second_dir_str=first_dir_str+"//"+a_sub_dirs
        new_second_dir_str=new_first_dir_str+"//"+a_sub_dirs
        create_dir_not_exist(new_second_dir_str)
        for every_excel_name in list(os.listdir(second_dir_str)): #遍历二级目录下文件
            print(every_excel_name)
            every_excel_path=second_dir_str+"//"+every_excel_name
            pd_read_excel_frame=pd.ExcelFile(every_excel_path)    #读取此目录下的excel
            sheet_names=pd_read_excel_frame.sheet_names
            xlsx = pd.ExcelWriter(new_second_dir_str+"//"+every_excel_name)  #读取excel文件
            a_new_col=[]
            for a_sheet_name in sheet_names:  #读取每一个sheet_name,写入每一个sheet
                    data_pd=pd_read_excel_frame.parse(a_sheet_name)
                    for every_row in data_pd.iterrows():
                        one_sentence=every_row[-1]["列名"]
                        a_new_col.append("newData")
                    data_pd["columnNew"]=allRelativeChineseList
                    data_pd.to_excel(xlsx, sheet_name=a_sheet_name)
            xlsx.save()
            xlsx.close()                                        #保存每一个新的文件

    2.2 excel文件写入

import xlwt        #pip install xlwt==1.3.0
column_name = ["学校名", "个人报名总数", "异常数量", "异常比率", "方差"] 
f = xlwt.Workbook()
sheet1 = f.add_sheet('sheet1', cell_overwrite_ok=True)
# 写入第一列作为元数据(标签数据)
for _ in range(len(column_name)):
sheet1.write(0, _, column_name[_]) # 写入列的标签元数据
sheet_hang=1
for a_data in data:    # 使用时只需替换data数据就行,a_index为0,已经写过元数据了
    sheet1.write(sheet_hang, column_name.index("学校"), data0[a_index][值1])
    sheet1.write(sheet_hang, column_name.index("报名总数"), data1[a_index][值2])
    sheet1.write(sheet_hang, column_name.index("数量"), data2[a_index][值3])
    sheet1.write(sheet_hang, column_name.index("比率"), data2[a_index][值3]
    sheet_hang+=1
f.save("文件名.xls")

自己封装的一个写文件示例类:

import xlwt
class ExcelWriter():
    def __init__(self, allColumn):
        self.excel = xlwt.Workbook()
        self.columnName = [oneColumnName for oneColumnName in allColumn]  
        self._sheet = self.excel.add_sheet('sheet1', cell_overwrite_ok=True)
        # 写入第一列作为元数据(标签数据)
        self.currentDataCount = 0
        for columnIndex in range(len(self.columnName)):
            self._sheet.write(self.currentDataCount, columnIndex, self.columnName[columnIndex])

    def write(self, columnDataDict):
        self.currentDataCount += 1
        for oneColumnName in columnDataDict:
                self._sheet.write(self.currentDataCount, self.columnName.index(oneColumnName), columnDataDict[oneColumnName])

    def saveExcel(self, dir="测试.xls"):
        self.excel.save(dir)

aaa=ExcelWriter(["hello1","hello2","hello3","hello4"])
aaa.write({"hello1":123})
print(aaa.currentDataCount)
aaa.write({"hello2":123,"hello1":234,"hello3":333})
aaa.saveExcel()

3  序列化数据读写文件

#读文件
import pickle
a_dict1={"user":"xiaoming","movie":["love","comic","et."]}
with open("adict.txt","wb") as f:
    data_dumps = pickle.dumps(a_dict1)
    f.write(data_dumps)

#写文件
with open("adict.txt", "rb") as f:
    a_dict2 = pickle.loads(f.read())
    print(a_dict2)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值