向定宽文本文件添加分隔符

1 投票
2 回答
1127 浏览
提问于 2025-05-01 16:02

我正在尝试给一个固定宽度的文本文件添加分隔符。

到目前为止,我的代码是这样的:

list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
with open('output.txt', 'w') as outfile:
    with open('input.txt', 'r') as infile:
        for line in infile:
            newline = line[:4] + '|' + line[4:]
            outfile.write(newline)
outfile.close()

上面的代码在第5个字节的位置插入了一个管道符(|)。现在我想在列表中的下一个值(29)的位置也插入一个管道符。我使用的是Python 2.7。

暂无标签

2 个回答

0

这是一个快速的小技巧。看看它是否有效:

list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
with open('output.txt', 'w') as outfile:
    with open('input.txt', 'r') as infile:
        for line in infile:
            for l in list:
                newline = line[:l] + '|' + line[l:]
                outfile.write(newline)
# outfile.close() -- not needed
2

我觉得你想要做的就是这个:

list=[4,29,36,45,70,95,100,111,115,140,150,151,152,153,169]
with open('output.txt', 'w') as outfile:
    with open('results.txt', 'r') as infile:
        for line in infile:
            iter = 0
            prev_position = 0
            position = list[iter]
            temp = []
            while position < len(line) and iter + 1 < len(list):
                iter += 1
                temp.append(line[prev_position:position])
                prev_position = position
                position = list[iter]
            temp.append(line[prev_position:])

            temp_str = ''.join(x + "|" for x in temp)
            temp_str = temp_str[:-1]

            outfile.write(temp_str)

这个代码会读取一个输入文件,并在列表中的特定位置插入一个|符号。这样做可以处理比你列表中的值更小或更大的情况。

撰写回答