【发布时间】:2018-09-27 13:09:19
【问题描述】:
我的任务是使用在文本文件中提供给我的 SAP 自定义报告 - 下面的示例(已删除名称并将此示例的所有值设为 0.00)。任务是使用这些数据并根据这些数据创建 xlsx 文件。我在特定文件夹中有 100 个这些 txt 文件。我如何将它加载到 python 中并创建一个 xlsx 文件,该文件将标题数据保存在每个文件的表格上方相同的位置/格式中?
我有下面的代码为每个文件创建 xlsx,但格式都搞砸了。我需要为每个单元格/列/行提供更好的格式。
非常感谢任何帮助!
当前代码:
import glob
import os
from xlsxwriter import Workbook
filepath = 'mypath'
txtfiles = glob.glob(os.path.join(filepath, '*z*.txt*'))
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
for filename in txtfiles:
readfiles = open(filename, 'r')
row_list = []
for row in readfiles:
row_list.append(row.split('\n'))
column_list = zip(*row_list)
workbook = Workbook(filename.replace('.txt', '.xlsx'))
worksheet = workbook.add_worksheet('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))
else:
worksheet.write(item, i, value)
i += 1
workbook.close()
下面的示例报告:
SAMPLE REPORT TEMPLATE
Page Number: 1 of 1 Time of Output:06:37:00
Author of Report:ME Date of Output:09/27/2018
Ledger:SAMPLE Version: 1
Currency: USD Fiscal Year:2018
Report Group:RANDOM Period: 0 to 10
|. | Outside MONEY | Outside MONEY2 | Outside MONEY3 | Subtotal MONIES |
|------------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|
| INCOME MONIES BEFORE CERTAIN CALCULATIONS SAMPLE | 0.00 | 0.00 | 0.00 | 0.00 |
|------------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|
| 1 - Line Data 1 | 0.00 | 0.00 | 0.00 | 0.00 |
| 1 - Line Data 2 | 0.00 | 0.00 | 0.00 | 0.00 |
| 1 - Line Data 3 | 0.00 | 0.00 | 0.00 | 0.00 |
| 1 - Line Data 4 | 0.00 | 0.00 | 0.00 | 0.00 |
| 1 - Line Data 5 | 0.00 | 0.00 | 0.00 | 0.00 |
| 2 - Line Data 1 | 0.00 | 0.00 | 0.00 | 0.00 |
| 2 - Line Data 2 | 0.00 | 0.00 | 0.00 | 0.00 |
| 2 - Line Data 3 | 0.00 | 0.00 | 0.00 | 0.00 |
|* Sample Random Line W/ Star | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 - Line Data 1 | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 - Line Data 2 | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 - Line Data 3 | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 - Line Data 4 | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 - Line Data 5 | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 - Line Data 6 | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 - Line Data 7 | 0.00 | 0.00 | 0.00 | 0.00 |
| 3 - Line Data 8 | 0.00 | 0.00 | 0.00 | 0.00 |
【问题讨论】:
-
是的,逐行读取txt文件并在python列表或字典中收集数据相对容易。无需为此使用熊猫。然后,您可以使用 XlsxWriter (xlsxwriter.readthedocs.io) 将它们写为 excel。如果您需要更多帮助,请尝试并发布您拥有的代码。
-
@576i 你会使用 readlines() 还是 list?抱歉,我从来没有做过这样的事情,因为我通常使用容易作为表格上传到数据框中的文件。
-
with open ('filename') as f1: for line in f1: do something with line... -
标签: python python-3.x pandas