python - 如何在每一行中添加制表符?
问题描述
我有这样的文件
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
解决方案
您可以使用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
推荐阅读
- ios - UIRefreshControl Selector 不调用目标 c
- sql - 检查与 SQL Server 2000/2005 的连接详细信息
- spring-boot - 为什么千分尺不会停止向 datadog 发送数据并已经关闭?
- apache-kafka - 如何知道何时在 Kafka 中提交记录?
- python - 使用命令单击绑定按钮(在 tkinter 上)
- automation - 克洛夫安装失败
- apache-kafka - Kafka jdbc sink 连接器不正确转换时间戳
- java - 根据阈值限制从数组中删除项目?
- selenium-webdriver - 在设置 Gemini url 之前设置 localStorage 或全局变量
- php - Codeigniter 3 博客错误:分页仅显示第一页