[英]Write multiple text files to one excel workbook on different sheets?
I have multiple text files with information such as the following: 我有多个文本文件,其中包含以下信息:
Agilent Technologies, Inc.
Date|Previous Close|Open|Day Low|Day High
2017-02-12|$50.47|$50.51|$50.02|$50.59
Each text file is named by its ticker
that is located on a new line of the text file master.txt
. 每个文本文件由其命名的
ticker
是位于文本文件的新线master.txt
。 I want one workbook with the above data on each sheet which should be named by the ticker
therefore I used the following code: 我想要一个工作簿,其中每张纸上都有上述数据,应该由
ticker
来命名,因此我使用以下代码:
import xlwt
textfile = "C:/Python27/SublimeText/Stocks/Master/Excel.txt"
with open("master.txt", 'r') as f:
tickers = [line.rstrip('\n') for line in f]
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
style = xlwt.XFStyle()
style.num_format_str = '#,###0.00'
for ticker in tickers:
try:
f = open("%s.txt" % ticker, 'r+')
except:
pass
row_list = []
for row in f:
row_list.append(row.split('|'))
column_list = zip(*row_list)
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('%s' % ticker)
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'))
When running the above code each ticker
overwrites the last instead of adding a new sheet. 运行上面的代码时,每个
ticker
代号都会覆盖最后一个ticker
,而不是添加新的工作表。 Another issue is that data is only transferred to the first column. 另一个问题是数据仅传输到第一列。 For example, the example text file I gave above looks like the following in Excel:
例如,我上面给出的示例文本文件在Excel中看起来类似于以下内容:
Agilent Technologies, Inc.
Date
2017-02-12
workbook = xlwt.Workbook() # moved outside the loop
for ticker in tickers:
with open("%s.txt" % ticker, 'r') as f:
worksheet = workbook.add_sheet('%s' % ticker)
for row, line in enumerate(f):
line = line.rstrip()
for col, value in enumerate(line.split('|')):
if is_number(value):
worksheet.write(row, col, float(value), style=style)
else:
worksheet.write(row, col, value)
workbook.save('all_the_files.xls'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.