Python之本地数据读写

1、基于open的本地数据读写,可以使txt格式也可以是xls,CSV等格式。

        文件存储:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
data=['test1','test2','test3']
f=open('sample.txt','w')
for i in data:
    f.write(i)
    f.write('\n')
f.close()

        文件读取:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
f= open('sample.txt', 'r')#打开文件,如果不存在就创建
for i in f.readlines():
    print(i)
# for i in f.read():
#     print(i)
# for i in f.readline():
#     print(i)
f.close()#关闭文件

        open第二个参数的几种形式:

        r:只读,文件必须存在;

        rb,以二进制的方式打开;

        w:只写,文件不存在则创建,文件存在则覆盖;

        wb:以二进制方式存储;

        r+:读写,文件必须存在,写入时会清空原内容;

        w+:读写,文件不存在则创建,文件存在则覆盖;

        a+:读写,文件不存在则创建,文件存在则在后面追加内容。

        文件中的换行空格:一般\n换行,\t空格;\r换行,\b空格,\a空格,\f空格,\v空格,

2、基于xlwt、xlrd的Excle文件读写:

        Excle文件文件保存:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
import xlwt
import xlrd
def set_style(name, height, bold=False):
    """
    输入样式设置
    :param name:字体名
    :param height: 行高
    :param bold: 宽
    :return:
    """
    style = xlwt.XFStyle()  # 初始化样式
    font = xlwt.Font()  # 为样式创建字体
    font.name = name  # 'Times New Roman'
    font.bold = bold
    font.color_index = 4
    font.height = height
    style.font = font
    return style

data = ['test1', 'test2', 'test3']
try:
    f = xlrd.open_workbook("sample.xls")#尝试打开
except:
    f = xlwt.Workbook()  # 不纯在就创建工作簿
sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)  # 创建sheet
for j in range(3):
    for i in range(0, len(data)):
        sheet1.write(j, i, data[i], set_style('Times New Roman', 220, True))#行、列、数据、数据存储类型
f.save("sample.xls")

        Excle文件读取:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
import xlwt
import xlrd
f=xlrd.open_workbook("sample.xls")
table = f.sheets()[0]
print(table.nrows)#行数
print(table.ncols)#列数
# 单元格操作cell
for i in range(table.nrows):
    for j in range(table.ncols):
        print(table.cell(i,0).value)#行
        print(table.cell(0,i).value)#列
        print(table.cell(i,j).value)
# 使用行列索引
for i in range(table.nrows):
    print(table.row(0)[i].value)#第一行
    print(table.col(0)[i].value)#第一列

3、通过numpy.loadtxt导入文件:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
import numpy as np
data=np.loadtxt('sample.txt',dtype=bytes,delimiter='\n')#存放在一个数组中
print(data)
print(len(data))

4、基于openpyxl的excel数据读入:对于Excel的输入写入在python集中常用的数据库中还是openpyxl相对好用,可以对写入数据进行格式绘图等设置;读取的话推荐xlrd,因为它支持.xls和.xlsx两种格式。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
import openpyxl
import os

def write_excel(self, excelname='test.xlsx', sheetname='test', data=[['test',[['test','test','test'],[1,4,5,5,8,9,10],[5,'singweek',7,8,9]]]], file=False):
    """
    excel数据写入操作
    :param excelname:操作的excel文件名
    :param sheetname:操作odeexcel sheet表名
    :param data:需要写入的数据
    :param file:存储地址,需要自己填写文件夹路径'.\\data\\',相对路径或者绝对路径
    :return:1写入成功
    """
    if os.path.exists(file) is True:
        pass
    else:
        os.makedirs(file)
    write_filename = file + excelname + '.xlsx'  # 地址拼接
    excelnum = len(sheetname)
    # 如果excel存在则调用,不存在则重新创建一个新表将数据写入
    if os.path.exists(write_filename) is True:  # 要操作的excel已经存在
        excel = openpyxl.load_workbook(write_filename)
        wb = excel.active
        for i in range(excelnum):  # 循环遍历需要写入的表,并将数据吸入
            wc = excel[sheetname[i]]
            if sheetname[i] == data[i][0]:  # sheet表名比对
                for row in range(len(data[i][1])):
                    wc.append(data[i][1][row])  # 按行写入数据
            else:
                print("sheet名不匹配,请重新输入,%s" % sheetname)
    else:  # 要操作的excel不存在,新建一个表
        excel = openpyxl.Workbook()
        ws = excel.active
        for i in range(excelnum):  # 循环创建sheet表
            wb1 = excel.create_sheet(title=sheetname[i], index=i)
            if sheetname[i] == data[i][0]:  # sheet表名比对
                for row in range(len(data[i][1])):
                    wb1.append(data[i][1][row])  # 按行写入数据
            else:
                print("sheet名不匹配,请重新输入,%s" % sheetname)
    excel.save(write_filename)  # 存储
    excel.close()  # 关闭
    return True

openpyxl的官网,更多excel相关操作可以查阅:https://openpyxl.readthedocs.io/en/stable/validation.html

猜你喜欢

转载自blog.csdn.net/zx520113/article/details/84946092