【20171224】文件操作
1、读写txt
#coding=utf-8 # 读文件 def read_file(): # 读取文件 read_txt = open('txt/read_txt','r') # 一次读取一行 oneline = read_txt.readline() print('oneline:\n',oneline) # 一次读取所有行【接着上一条读取结束往下读】 for line in read_txt.readlines(): print('lines:\n',line) # 一次读取所有【接着上一条读取的往下读】 all = read_txt.read() print('all:\n',all) read_txt.close() read_file() # 写文件 def write_file(): # w:只写模式【不可读;不存在则创建;存在则清空内容】 write_txt = open('txt/write_txt','w',encoding='utf-8') write_txt.write('hello\nnihao') write_txt.write('你好') # w+,写读【可读,可写】,消除文件内容,然后以读写方式打开文件。 write_txt2 = open('txt/write_txt2','w+',encoding='utf-8') write_txt2.writelines('writelines:你好') write_txt2.writelines('writelines:hello') write_txt.close() write_txt2.close() write_file()
2、写excel
#coding=utf-8 # xlwt写excel文件 import xlwt # xlwt写文件 def write_file(): # 新建excel # write_excel = xlwt.Workbook(encoding='utf-8') write_excel = xlwt.Workbook(encoding='ascii') # 一般建议用 ascii 编码 # 新建sheet table = write_excel.add_sheet('sheet1',cell_overwrite_ok=False) # cell_overwrite_ok=False,当对一个单元格重复操作时,加这个不会报错 # 写入数据 row = 1 col = 2 table.write(row,col,'yy') table.write(1,1,u'你好') table.write(0,0,label = 'Row 0, Column 0 Value') # 建第二个 sheet table2 = write_excel.add_sheet('sheet2',cell_overwrite_ok=True) # 保存文件 write_excel.save('excelFile\writeFile.xls') def main(): write_file() if __name__ == '__main__': main()
3、读excel
#coding=utf-8 ''' 【【知识点】编解码】操作excle,要导入 xlrd 005_模块,需要安装 xlrd ''' import xlrd # 打开excle文件读取数据 data = xlrd.open_workbook('test.xlsx') # 获取工作表 table = data.sheet_by_name(u'Sheet1') # 通过名称获取 table1 = data.sheets()[0] # 通过索引获取 table2 = data.sheet_by_index(0) # 通过索引获取 # 获取整行或整列数据 print('rowValue = ',table.row_values(1)) print('colValue = ',table.col_values(0)) # 获取行数或列数 print('nRows = ',table.nrows) print('nCols = ',table.ncols) # 循环输出行数据 nrows = table.nrows for i in range(nrows): print('循环输出行数据:',table.row_values(i)) # 单元格 print('cell_A1 = ',table.cell(0,0).value) # 使用单元格 print('cell_B2 = ',table.row(1)[1].value) # 使用行数的索引