文件操作
execl
模块:xlrd(读)
读取的类型应为*.xls文件
使用步骤:
1、打开文件
1.1 open_workbook(path),打开excel文件,返回一个文件对象
2、 获取文件中的sheet名称
2.1 sheets(),返回excel文件中所有的sheet对象,通过对象调用name返回sheet名称
2.2 sheet_names(),返回excel文件中所有sheet的名称
2.3 sheet_by_name(sheet_name),通过sheet名称获取指定的表
2.4 sheet_by_index(index),通过索引获取指定的表
3、通过sheet名称获取指定表中的数据
行
nrows,返回sheet中的行数
row_values(row),获取指定行中的数据,row为行号
列
ncols,返回sheet中的列数
col_values(col),获取指定列中的数据,row为列号
单元格
cell_values(row,col),返回指定单元格的数据
import xlrd # xlrd需要安装1.2.0版本才能使用xlsx格式
f = xlrd.open_workbook('/home/cjp/桌面/HDMI/1.xlsx') # 打开excel文件
print(f)
sheets = f.sheets() # 获取所有的sheet对象
print(sheets[1].name) # 通过索引获取sheet名称
sheet = f.sheet_by_index(1) # 通过索引获取sheet对象
row = sheet.nrows # 获取行数
print(row)
print(sheet.row_values(2)) # 以列表的形式返回相应行的内容
print('******************')
col = sheet.ncols # 获取列数
print(col)
print(sheet.col_values(0)) # 以列表的形式返回相应列的内容
文本文件
打开文件
语法:open(file[,mode=type,encoding=编码]),打开指定文件,返回一个文件对象
file,表示待操作的文件,相对路径、绝对路径都行(不能是目录)
mode,表示打开文件方式,如果省略则表示只读模式
r,只读,如果指定的文件不存在系统报错
w,覆盖写入,如果指定的文件不存,系统会自动创建该文件,然后执行写入操作
a,追加写入,如果指定的文件不存,系统会自动创建该文件,然后执行写入操作
b,表示二进制,一般用于对图片类的文件操作
encoding,指定编码(如果打开文件提示错误,再加上encoding参数)
常用方法
closed,检查文件是否为关闭状态,如果是返回True,否则返回False
close(),关闭文件
encoding,返回打开文件的编码
f = open(file='for.py',mode='r')
print(f.encoding) # 返回打开文件的编码 UTF-8
print(f.closed) # 检查文件是否关闭 False
f.close() # 关闭文件
print(f.closed) # 检查文件是否关闭 True
读文件
read(),将文件的所有内容读取处理,保存在字符串中
readline(),读取文件中的一行,保存在字符串中
readlines(),将文件的所有内容读取处理,保存在列表中,文件中的每一行为列表中的一个元素
f = open(file='./user',mode='r')
# s = f.read()
# s = f.readline()
s = f.readlines()
print(s)
写文件
write(s),将一个字符串写入文件
f = open(file='./user',mode='w')
f.write('abc\t123456\nabd\t123456')
f.close()
writelines(iter),将一个可迭代对象的所有元素写入文件
f = open(file='./user',mode='a')
li = ['abc\t123456\n','abc\t123452']
f.writelines(li)
f.close()
csv文件
模块:csv
使用步骤:
打开文件(open)
读取内容(csv.rader())
import csv
f = open('/home/cjp/桌面/HDMI/1.csv')
data = csv.reader(f)
for i in data:
print(i)
f.close()
with语句
管理上下文,可以实现打开文件后自动关闭
语法:with open(file) as f:
import csv
with open('/home/cjp/桌面/HDMI/1.csv') as f: # 自动关闭文件
data = csv.reader(f)
for i in data:
print(i)
.xls,.xlsx 指定位置写入数据
import xlrd
import xlwt
from xlutils.copy import copy
import os
filename = '/home/cjp/桌面/HDMI/data.xlsx' # 文件路径
# 打开excel
rb = xlrd.open_workbook(filename)
# 复制excel
wb = copy(rb)
# print(type(wb))
# 从复制的excel文件中,得到第一个sheet
sheet = wb.get_sheet(0)
# print(type(sheet))
sheet.write(5,0,'nihao')
sheet.write(4,0,'n')
sheet.write(3,0,'i')
os.remove(filename)
wb.save(filename)