【发布时间】:2016-01-03 12:06:31
【问题描述】:
我目前正在尝试将我拥有的文本文档导出/转换为 .xls 文件。因此,根据我的发现,我能够创建一个 xls,但现在我只需要从文本文档中获取正确的 xls 格式。
这是我正在尝试做的一个例子。
假设我有以下文本文档:numbers.txt
|<DOg>|
|Data1 = 300 |
|Data2 = 200 |
|Data3 = 15 |
|Data4 = 14 |
|Data5 = 4 |
|<DOg>|
|Data1 = 800 |
|Data2 = 500 |
|Data3 = 25 |
|Data4 = 10 |
|Data5 = 5 |
如果我使用| 作为分隔符运行我的代码,我会收到这个 .xls 文件
如您所见,格式已关闭。
我试图达到的目标是以下格式。
我目前使用的代码如下:
mypath = raw_input("Please enter the directory path for the input files: ")
from os import listdir
from os.path import isfile, join
textfiles = [ join(mypath,f) for f in listdir(mypath) if isfile(join(mypath,f)) and '.txt' in f]
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
import xlwt
import xlrd
style = xlwt.XFStyle()
style.num_format_str = '#,###0.00'
for textfile in textfiles:
f = open(textfile, 'r+')
row_list = []
for row in f:
row_list.append(row.split('|'))
column_list = zip(*row_list)
# for column_list in f:
# column_list.append(column.split('|'))
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
i = 0
for column in column_list:
for item in range(len(column)):
value = column[item].strip()
if is_number(value):
worksheet.write(item, i, float(value), style=style)
else:
worksheet.write(item, i, value)
i+=1
workbook.save(textfile.replace('.txt', '.xls'))
我的想法是对列使用.split() 方法,但是我不确定如何正确实施,因为当我对列使用split 时,每一行最终都是它自己的列。
【问题讨论】:
标签: python excel split xlrd xlwt