【Python笔记】操作读取Excel文件、文本文件

需求:读取Excel文件、替换文本文件中得指定某个字串并生成新的文件

源代码:

#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()
1.打开表格,获取表格得行数列数
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()

猜你喜欢

转载自blog.csdn.net/Beyond_1024/article/details/80176212