2014-11-04 85 views
1

我試圖將分隔符添加到固定寬度文本文件。將分隔符添加到固定寬度文本文件

這是我迄今:

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

你的代碼中使用的變量「list」是如何的? – 2014-11-04 21:33:43

+0

我認爲這不符合你的想法:'line [:4]'和'line [4:]' – KronoS 2014-11-04 21:34:30

+0

尚未使用。 – swhit 2014-11-04 21:34:38

回答

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) 

這需要輸入文件並插入|在列表中的位置。這將處理小於或大於列表中的值的個案。

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 
+0

這是假設每行長度> 169個字符。此外,每次迭代都會改變大小。你需要解釋這一點。 – KronoS 2014-11-04 21:39:10

+0

@KronoS你是對的我的壞,但讓我們看看swhit想要什麼。也許迭代器會從列表中獲取下一個值 – 2014-11-04 21:39:52