【问题标题】:how to convert text file to Excel file , Without deleting the spaces between data如何将文本文件转换为 Excel 文件,而不删除数据之间的空格
【发布时间】:2019-09-02 19:25:55
【问题描述】:

我想将文本文件转换为 excel 文件,而不删除每一行的空格。

请注意,列数将等于文件的所有行数。

文本文件遵循以下格式:

第一行

05100079 0000001502 5 01   2 070 1924    02 06 1994 C508 2 8500 3 8500 3 3 1 1 012 10    0 98 00                       4 8 8 9                                                                                               0    40       01              2 15      26000 1748 C508       116 102 3  09 98 013 1 1 0 1 10 10       0 09003     50060 50060 0 0  369 99 9       1 4 4 5 8                          0 0181                        1 80 00 01 0            9 9       8        1 0 00 00 020 0

第二行

05100095 0000001502 2 01   2 059 1917    02 03 1977 C504 2 8500 3 8500 3 9 1 1                   54-11-0999-00         2     9                                                                                               0    90       01              2 12      26000 1744 C504       116 102 3  09 98 013 1 1 0 2             0 09011     50060 50060 0    36   9 9       1 9 9 5 8                          0 3161                                                9 9       8                  020 0             `

如何编辑代码将文本文件转换为excel文件而不删除数据之间的空格?

下面的这段代码删除了每一行的空格。

我的意思是将文件转换为Excel工作表而不对原始文件进行任何修改。

空格保持空格,所有其他数据保持相同格式。

import xlwt
import xlrd

book = xlwt.Workbook()
ws = book.add_sheet('First Sheet')  # Add a sheet

f = open('testval.txt', 'r+')

data = f.readlines() # read all lines at once
for i in range(len(data)):

    row = data[i].split()  # This will return a line of string data, you may need to convert to other formats depending on your use case`

    for j in range(len(row)):
        ws.write(i, j, row[j])  # Write to cell i, j

book.save('testval' + '.xls')
f.close()

预期输出: 与原始文件“文本”格式相同的Excel文件

【问题讨论】:

  • 你想对空格做什么?如果第 0 行是 'hello world' 单元格应该是什么样子?
  • 您想要一个只有一列包含文本文件每一行的 Excel 文件吗?
  • @james, 数据是数字和文字,空格代表一定的值,没有“疾病”或“病历”或者有未登记的数据,空间可以有价值,可以数据分隔符。
  • @LaurentLAPORTE,不,我通过空白原始文件中的值将所有字段彼此分开,但是有些值已经为空,我想要做的是按列分隔数据基于存在的空间
  • 那么,您希望每个单元格中有一个字符吗?你的分隔符是什么?你能编辑一个例子吗?

标签: python excel text


【解决方案1】:

如果你有固定长度的字段,你需要使用索引间隔分割每一行。

例如,你可以这样做:

book = xlwt.Workbook()
ws = book.add_sheet('First Sheet')  # Add a sheet

with io.open("testval.txt", mode="r", encoding="utf-8") as f:
    for row_idx, row in enumerate(f):
        row = row.rstrip()
        ws.write(row_idx, 0, row[0:8])
        ws.write(row_idx, 1, row[9:19])
        ws.write(row_idx, 2, row[20:21])
        ws.write(row_idx, 3, row[22:24])
        # and so on...

book.save("sample.xlsx")

你会得到类似的东西:

【讨论】:

  • LPORTE,非常感谢您,感谢您的合作
猜你喜欢
  • 2013-08-29
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 2015-04-11
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2019-01-31
相关资源
最近更新 更多