我试图将分隔符添加到固定宽度的文本文件中。
这就是我到目前为止:
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。
答案 0 :(得分: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)
这将获取输入文件并在列表中的位置插入|
。这将处理小于或大于列表中值的情况。
答案 1 :(得分: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