记录下一些常用的Python文件读取的用法,
一 Python读取xml
xml 类似文件目录,可理解为树状数据结构,其中每个节点有子节点,属性和test信息
(1)读取
①对该节点的操作,获取该node包含的信息
- node.tag 返回节点名称
- node.contrib 节点的属性
- node.text 该节点包含的内容,可以是int,string数据,或者是子节点
②对该节点子节点的操作
- 像操作列表一样通过下标访问各子节点,如root[0][2].text 返回根节点的第一个子节点的第三个子节点的text信息
- find通过子节点名字查找,并返回第一个查找结果
- find_all('object')返回所有名称为object的子节点
import xml.etree.ELementTree as ET
tree = ET.parse('/path/to/test.xml')
root = tree.getroot()
#可通过下标访问root的子节点,root[0]第一个子节点
#也可用for循环依次访问root的全部子节点
for child in root:
#输出该节点的名称, 属性
print(child.tag,child.attrib)
#find 返回子节点中第一个tag为size的节点
size = root.find('size')
#find_all 饭后字节点中所有名称为object的节点列表
for object in root.findall('object')
print(object.tag)
(2) 写入
- node.set()修改属性,如node.set('school','neu'),将节点的school设置为neu
- node.append()增加子节点,
- node.remove()删除子节点
二 python读写txt
(1) 读取
用readlines()返回读取全部行的列表,或者readline()读取一行,read()读取一个字符
with open('test.txt','r') as f:
for line in f.readlines():
print(line)
(2)写入
with open('/path/to/test.txt','a') as f:
f.write('some text')
三 Python读写csv
csv文件类似于excel表格,
(1)读取
与读取txt不同的只是换了文件的读取器而已
首先定义csv读取器,然后一行一行读取文件,
import csv
with open('/path/to/csvfile.csv','r') as csvfile:
reader = csv.reader(csvfile)
for line in reader:
print(line)
(2)写入
定义csv写入器,一行一行写入
with open('/path/to/csvfile','a',newline='') as csvfile:
writer = csv.writer(csvfile)
for line in data:
writer.writerow()
四 Python 读取HDF5
h5 file是按照字典格式存储的,直接通过关键字key读取或者写入
使用"h5py"模块来使用HDF5。该模块包含了文件、组、数据集以及特征等HDF对象的上层封装类
(1)写入
使用create_dataset方便对数据操作,可像numpy数组一样操作数据
import h5py
with h5py.File('/path/to/file.h5','a') as h:
h.create_dataset('train',data=train)
h.create_dataset('label',data=label)
(2)读取
h5['train']读取的是h5py dataset对象,需要用np.array()转化成numpy数组在使用
import h5py
import numpy as np
with open('/path/to/file.h5','a') as h5:
train = np.array(h5['train'])
label = np.array(h5['label'])
五 python 读写xls文件
使用xlrd,xlwt对xls文件进行读写操作
(1)读取
import xlrd
xls_file = '/path/to/xxx.xls'
wb = xlrd.open_workbook(xls_file)
sheet = wb.sheet_by_index(0)#获取第一个sheet
#按行读取
for i in range(len(sheet.nrows)):#sheet.nrows获取sheet的总行数
cur_row_value = sheet.row_values(i)
#按列读取
for i in range(len(sheet.ncols)):#sheet.ncols获取sheet的总列数
cur_row_value = sheet.col_values(i)
#读取指定单元格的内容
sheet.cell_value(0,0)#第0行0列单元格的内容
(2)写入
import xlwt
wb = xlwt.Workbook()
sheet = wb.add_sheet('mysheet')
nrows = 100 #自己定义要写入多少行
for i in range(nrows):
cur_row_value = 'whatever you what'
sheet.write(i,0,cur_row_value)
wb.save('/path/to/save/file.xls')