【Python筆記】操作讀取Excel檔案、文字檔案
阿新 • • 發佈:2018-11-11
需求:讀取Excel檔案、替換文字檔案中得指定某個字串並生成新的檔案
原始碼:
1.開啟表格,獲取表格得行數列數#encoding:utf-8 # -*- coding: utf-8 -*- #!/usr/bin/env python # -*- coding=utf-8 -*- #Using GPL v2 #Author: [email protected] #2010-10-27 22:07 import xlrd import xlwt from xlutils.copy import copy import os import re from datetime import datetime #from __future__ import division import fileinput import sys,time data = xlrd.open_workbook('IP1.xls') table = data.sheet_by_index(0) nrows = table.nrows #行數 ncols = table.ncols #列數 n = 0 print 'IP表有%d 行,%d 列'%(nrows,ncols) for i in range(0,9,1): string = table.cell(0,i).value if string !='': print table.cell(0,i).value print "==========================================" print table.cell(1,1).value print table.cell(i,1).value print table.cell(i,2).value print table.cell(i,6).value for i in range(1,37,1): infile = open("無線指令碼.txt", "r") #開啟檔案 outfile = open(str(i)+".txt", "w") # 內容輸出 for line in infile: #按行讀檔案,可避免檔案過大,記憶體消耗 string1 = table.cell(i,1).value string2 = table.cell(i,2).value string3 = table.cell(i,6).value n = int(table.cell(i,2).value) outfile.write(line.replace('shebei',str(string1)).replace('yewuVLAN',str(n)).replace('guanliIP',str(string3))) infile.close() #檔案關閉 outfile.close()
data = xlrd.open_workbook('IP1.xls')
table = data.sheet_by_index(0)
nrows = table.nrows #行數
ncols = table.ncols #列數
2.開啟文字檔案並且進行替換
infile = open("無線指令碼.txt", "r") #開啟檔案 outfile = open(str(i)+".txt", "w") # 內容輸出 for line in infile: #按行讀檔案,可避免檔案過大,記憶體消耗 string1 = table.cell(i,1).value string2 = table.cell(i,2).value string3 = table.cell(i,6).value n = int(table.cell(i,2).value) outfile.write(line.replace('shebei',str(string1)).replace('yewuVLAN',str(n)).replace('guanliIP',str(string3))) infile.close() #檔案關閉 outfile.close()