【20171224】文件操作
阿新 • • 發佈:2017-12-27
lose 名稱 label print open 取數據 for test 模塊
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) # 使用行數的索引
【20171224】文件操作