我正在尝试向固定宽度的文本文件添加分隔符。
这是我迄今为止所拥有的:
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。
最佳答案
我认为这就是您想要做的:
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)
这需要一个输入文件并在列表中的位置插入一个|
。这将处理小于或大于列表中的值的情况。
关于python - 向固定宽度文本文件添加分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26745405/