首页 > 解决方案 > 如何在每一行中添加制表符?

问题描述

我有这样的文件

237501.jpg#0 Two 
237501.jpg#1 Teddy
237501.jpg#2 Large 
237501.jpg#3 A teddy 
237501.jpg#4 an image 
237501.jpg#0 Two 
237501.jpg#1 Teddy
237501.jpg#2 Large 
237501.jpg#3 A teddy 
237501.jpg#4 an image  

我需要在每行的每个数字后添加制表符才能像这样

237501.jpg#0     Two 
237501.jpg#1     Teddy
237501.jpg#2     Large 
237501.jpg#3     A teddy 
237501.jpg#4     an image 

我的代码是

import os

inputFile = open("output1.txt", "r") 
exportFile = open("output10.txt", "w")
for line in inputFile:
   new_line = line.replace("#0", '#0    ')
   exportFile.write(new_line) 

但无法抓住每一行的数字我得到的结果是

237501.jpg#0     Two 
237501.jpg#1 Teddy
237501.jpg#2 Large 
237501.jpg#3 A teddy 
237501.jpg#4 an image 

标签: python

解决方案


您可以使用enumerate

input.txt

237501.jpg#0 Two 
237501.jpg#1 Teddy
237501.jpg#2 Large 
237501.jpg#3 A teddy 
237501.jpg#4 an image 
237501.jpg#0 Two 
237501.jpg#1 Teddy
237501.jpg#2 Large 
237501.jpg#3 A teddy 
237501.jpg#4 an image  

代码:

inputFile = open("input.txt", "r")
exportFile = open("output.txt", "w")
patterns = ["#"+str(idx) for idx in range(5)]
for line in inputFile:
    for pattern in patterns:
        if pattern in line:    
            new_line = line.replace(pattern, pattern+' '*3)
            exportFile.write(new_line)
            break
inputFile.close()
exportFile.close()

output.txt结果:

237501.jpg#0    Two 
237501.jpg#1    Teddy
237501.jpg#2    Large 
237501.jpg#3    A teddy 
237501.jpg#4    an image 
237501.jpg#0    Two 
237501.jpg#1    Teddy
237501.jpg#2    Large 
237501.jpg#3    A teddy 
237501.jpg#4    an image  

推荐阅读