2

我有一个 excel 文件,其中包含我需要在我的 PC 上使用的多列不同宽度的数据。但是,该文件包含 SOH 和 STX 字符作为分隔符,因为它们来自 Mac 上的 TextEdit。SOH 是记录分隔符,STX 是行分隔符。在我的电脑上,这两个字符都显示为一个矩形(在屏幕截图中)。我不能使用固定宽度分隔选项,因为我会丢失数据。我尝试编写 Python 脚本,但 Python 也不识别 SOH 和 STX,也将其显示为矩形。如何适当地分隔这些记录?我将不胜感激任何可能的方法。谢谢!

实际文本文件

在此处输入图像描述

4

1 回答 1

3

这应该工作

SOH='\x01'
STX='\x02'

# As it is, this function returns the values as strings, not as integers
def read_lines(filename):
    rawdata = open(filename, "rb").read()
    for l in rawdata.split(SOH + STX):
        if not l:
            continue
        yield l.split(SOH)

# Rows is a list. Each element in the list is a row of values
# (either a list or a tuple, for example)
def write_lines(filename, rows):
    with open(filename, "wb") as f:
        for row in rows:
             f.write(SOH.join([str(x) for x in row]) + SOH + STX)

编辑:示例使用...

for row in read_lines("myfile.csv"):
    print ", ".join(row)
于 2014-02-17T00:18:29.290 回答