python之文件读写

python常用的读取文件txt、csv、xml、Excel

一、读写txt文件

with open('001.txt', "w+") as f:
    f.write("这是一个文本文件")
    f.seek(0)
    print(f.read())

二、csv读写文件

"""
open('some.csv', newline='', encoding='utf-8')
     # 使用系统默认编码将文件解码为unicode可使用不同的编码解码文件
     # 如果newline=''没有指定,嵌入引用字段内换行符将不会被正确地解释
     # 默认读写用逗号做分隔符(delimiter),双引号作引用符
     # 用writer写数据None被写成空字符串,浮点型调用repr()转化成字符串。非字符串型数据被str()成字符串存储。
"""
with open('001.csv', 'w+', encoding="utf-8", newline="") as f:
    csv_writer= csv.writer(f, dialect='excel')
    csv_writer.writerow(["lisi", 20, "专科"])
    csv_writer.writerow(["zhangsan", 18, "本科"])
    csv_writer.writerows([['xiao',5, ""], ['xiao02', 14, "中学"]])
    f.seek(0)
    print(f.read())

有时在程序中可以正常输出中文,但是用excel打开csv文件时会出现乱码,是因为excel能够正确识别用gb2312、gbk、gb18030或utf_8 with BOM 编码的中文,如果是utf_8 no BOM编码的中文文件,excel打开会乱码。可以使用GBK编码方式读写文件

三、xml读写文件

首先,生成一个简单的xml文件

#基本原理
#1.使用xml.dom.minidom这个module来创建xml文件
#2. 每个xml文件都是一个Document对象,代表着内存中的DOM树
#3.有了空的DOM树后,添加根节点
#4.创建其它的节点
#5.输出到xml文件中去
#创建一个xml文件
from xml.dom.minidom import Document
from xml.dom.minidom import parse
doc = Document()
#创建根节点
root_node = doc.createElement('Document')
#设置命名空间
root_node.setAttribute('content_method', 'full')
#文档中拼接节点
doc.appendChild(root_node)
#根节点下创建子节点1
item_node_1 = doc.createElement('item')
root_node.appendChild(item_node_1)
#item_node节点下创建文本节点
item_text = doc.createTextNode('项目名称1:报告')
item_node_1.appendChild(item_text)

#根节点下创建子节点1
item_node_2 = doc.createElement('item')
root_node.appendChild(item_node_2)
#item_node节点下创建文本节点
item_text = doc.createTextNode('项目名称2:投资交易')
item_node_2.appendChild(item_text)

#生成xml文件
f= open('abc.xml', 'w+', encoding='utf-8')
doc.writexml(f,indent='\t', addindent="\t", newl="\n", encoding='utf-8')
f.close()

生成格式如下:

<?xml version="1.0" encoding="utf-8"?>
    <Document content_method="full">
        <item>项目名称1:报告</item>
        <item>项目名称2:投资交易</item>
    </Document>

解析并更新xml文件内容

#解析xml, 并更新xml
docTree = parse('abc.xml')
item_nodes = docTree.getElementsByTagName("item")
for item in item_nodes:
    print(item.childNodes[0].data)

item_nodes[0].childNodes[0].data = 'O32'
with open('abc.xml', 'w+', encoding='utf-8') as f:
     docTree.writexml(f, indent='', addindent="", encoding='utf-8')

四、读取Excel文件

import openpyxl
excel_file_path = r'E:\case1.xlsx'
workbook= openpyxl.load_workbook(excel_file_path)
#遍历工作薄中的每个sheet页
for sheet_name in workbook.sheetnames:
    #获取Worksheet对象
    sheet = workbook[sheet_name]
    #读取行生成器中的数据,其实就是根据sheet.iter_rows()来生成行数据
    #sheet.values是一个生成器对象,返回的是cell对象中的值组成的元组
    #sheet.iter_rows是一个生成器对象,返回的是cell对象组成的元组
    for row_index , row_datas in enumerate(sheet.values):
        for col_index in range(0, sheet.max_column):
            print(row_datas[col_index], end=' ')
            #判断第一列数据是否是整型
            if isinstance(row_datas[0], int):
                # 利用sheet.cell(row=x,column=y).value对cell中的值进行更新
                sheet.cell(row=row_index+1, column=1).value = "T" + str(row_datas[0])
        print()
    #按行进行读取
    for row in sheet.iter_rows():
        for col_index in range(0, sheet.max_column):
            print(row[col_index].value, end=' ')
        print()
workbook.save(excel_file_path)

五、简单了解一下numpy、pandas

NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合,以 0 下标为开始进行集合中元素的索引。

ndarray 对象是用于存放同类型元素的多维数组。

"""
#pandas用法
pandas有两个主要数据结构:Series和DataFrame
Series是一种类似于一维数组的兑现个,它由一组数据(各种NumPy数据类型)和一组与之相关的数据便签(即索引)组成
pd.Series(data,index=[])
Series和ndarray之间的主要区别在于Series之间的操作会根据索引自动对齐数据

DataFrame是一个表格型的数据类型,每列值的数据类型可以不相同,常用的pandas对象
DataFrame既有行索引也有列索引,它可以被看做由Series组成的字典(共用同一个索引)
pd.DataFrame(data,columns = [ ],index = [ ]), 其中columns和index为指定的列、行索引
"""

import numpy as np, pandas as pd

#np.arange返回的均匀间隔值的numpy.ndarray对象数组
arr= np.arange(10)
print(arr, type(arr)) #输出结果:[0 1 2 3 4 5 6 7 8 9] <class 'numpy.ndarray'>
s = pd.Series(arr,)
print(s, type(s))
#输出结果如下:
# 0    0
# 1    1
# 2    2
# 3    3
# 4    4
# 5    5
# 6    6
# 7    7
# 8    8
# 9    9
#创建DataFrame最常用的是直接传入一个由等长列表或NumPy数组组成的字典
data={'state':['hello', 'world'], 'year':[2019, 2020], 'pop':[1.5,1.6]}
print(data, type(data))
#1)当不指定行索引index, 列索引columns时会自动加上行索引,字典的键会被当做列索引。
df = pd.DataFrame(data)
print(df)
#2)如果创建时指定了columns和index索引,则按照索引顺序排列
#如果传入的列在字典的key中找不到,当做缺省值NaN处理
df2 = pd.DataFrame(data, index=['one','two'], columns=['year', 'state', 'pop_title'])
print(df2)
#输出结果
#      year  state pop_title
# one  2019  hello       NaN
# two  2020  world       NaN

#3)另外一种常见的创建DataFrame方式是使用嵌套字典,
# pandas会被解释成外层字典的键作为列,内层字典的键作为行索引
data = {'state':{'one':'hello', 'two':'world'}, 'year':{'one':2019, 'two':2020}, 'pop':{'one':1.5, 'two':1.6, 'three':1.8}}
df3 = pd.DataFrame(data)
print(df3)
#输出结果
#        state    year  pop
# one    hello  2019.0  1.5
# two    world  2020.0  1.6
# three    NaN     NaN  1.8

 pandas处理Excel文件

"""
pandas如何读取并处理Excel中的数据呢?
"""
#pandas读取excel依赖于xlrd,需要安装xlrd#pd.read_excel返回数据类型object <class 'pandas.core.frame.DataFrame'>
df = pd.read_excel('case1.xlsx')
#打印指定的列数据
print(df['编号'] ,type(df))
#打印2行5列数据,注意pandas处理数据中一些特殊数据处理不了默认NaN
print(df.iloc[:2,:5])

 

posted @ 2020-10-17 23:27  *游鱼  阅读(283)  评论(0)    收藏  举报