文件及目录操作

python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块,主要用到的几个函数是,

import os

返回指定目录下的所有文件和目录名: os.listdir()
重命名:os.rename(old, new)
创建多级目录:os.makedirs()
创建单个目录:os.mkdir()
获取文件属性:os.stat(file)
修改文件权限与时间戳:os.chmod(file)
终止当前进程:os.exit()
获取文件大小:os.path.getsize(filename)

数据读取

读取 excel 文件

Python 读取 excel 需要调用 xlrd 模块

import xlrd

## 从给定的文件路径读取 excel 文件
data_1 = xlrd.open_workbook(file_path)

## 获取 excel 中 的表格,默认从 0 开始
table = data_1.sheets()[0]

## 读取表格中的每一行或者每一列
table.row_values(i)
table.col_values(i)

## 读取表格中单元格的数据
##cell_A1 = table.cell(0,0).value
##cell_C4 = table.cell(2,3).value

## 获取表格的行数和列数
nrows = table.nrows
ncols = table.ncols

## 打印表格的内容
for i in range(1, 10):
      print table.row_values(i)    # 打印每一行
      print table.col_values(i)    # 打印每一列

读取 MATLAB .mat 文件

Python 读取 .mat 文件需要用到 scipy.io 模块

dic_mat = scipy.io.loadmat(file_path) 
# 将 .mat 文件装入一个 dictionary 中 
print type(dic_mat) 
# 查看相应的 key name  
print dic_mat.keys() 

# 读取 key name 所对应的数组
data_mat=dic_mat['key_name']
posted on 2016-10-29 10:37  未雨愁眸  阅读(154)  评论(0编辑  收藏  举报