您的位置:首页 > 编程语言 > Python开发

用Python3 编写excel和txt的转换工具

2013-03-14 21:21 393 查看
前段时间为了给一个程序做语言包自动导入导出工具,发现Python做工具还是挺好用的,尤其是对各种编码的支持。

安装xlwt3和xlrd3,它们是针对Python3的版本。

将lang下的日文语言包导出到一个excel里:

点击(此处)折叠或打开

import os

import glob

path = os.getcwd()

files = glob.glob('../trunk/Resource/lang/ja/*.txt')

import xlwt3

if len(files)
> 0:

wb = xlwt3.Workbook()

for file in files:

fileName = file.split('\\')[1].split('.')[0]

print(fileName)

ws = wb.add_sheet(fileName)

with open(file, encoding='utf-8') as a_file:

line_number = 0

for a_line
in a_file:

a_line = a_line.rstrip()

mark = a_line.find("=")

ws.write(line_number, 0, a_line[0:mark])

ws.write(line_number, 1, a_line[mark+1:])

ws.col(0).width
= 8000

ws.col(1).width
= 40000

line_number += 1

a_file.close()

wb.save('langPack_ja.xls')

将sourceExcel下的excel文件导出为各txt文件:

点击(此处)折叠或打开

import os

import glob

import xlrd3 as xlrd

import re

path = os.getcwd()

files = glob.glob('sourceExcel/*')

for file in files:

wb = xlrd.open_workbook(file)

for sheetName
in wb.sheet_names():

txtFile = open('outputTxts/'
+ sheetName +
'.txt', mode='w', encoding='utf-8')

sheet = wb.sheet_by_name(sheetName)

for rownum
in range(sheet.nrows):

v1 = sheet.cell(rownum, 0).value

if
(type(v1)
== float):

v1 = str(v1)

v1 = re.sub('\.0*$',
"", v1)

v1 = v1.rstrip()

v2 = sheet.cell(rownum, 1).value

if
(type(v2)
== float):

v2 = str(v2)

v2 = re.sub('\.0*$',
"", v2)

v2 = v2.rstrip()

dataStr = v1
+ '=' + v2
+ '\n'

txtFile.write(dataStr)

txtFile.close()
http://blog.chinaunix.net/uid-20593721-id-3228789.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: