有时候生成txt文件,会一不小心忘了加换行,导致所有item都在一行,但希望每个item在独立地一行。每个item的字符串都是满足一定的特点的,因而可以通过插入'\n'的方法作修改。
比如,有一文件“1.txt”的内容是“word_1.png,Latinword_2.png,Latinword_3.png,Latinword_4.png,Latinword_5.png,Latin”,只有一行。那么就这样去改:
import re
with open("1.txt",'r') as f:
s = f.readlines() # 注意这是一个列表
s_list = list(s[0]) # 字符串转化为列表,便于插入
loc = [here.start() for here in re.finditer('word', s[0])] # 寻找匹配的位置
loc = loc[1:]
loc.reverse() # 很重要!如果从前向后插入的话,后面的位置序号会因前面的先插入而被打乱
for idx in iter(loc):
s_list.insert(idx, '\n') # 插入字符(这里是换行)
s1 = ''.join(s_list) # 从列表转化为字符串
with open("1.txt",'w') as f:
f.writelines(s1) # 存储结果
这样就得到了
word_1.png,Latin
word_2.png,Latin
word_3.png,Latin
word_4.png,Latin
word_5.png,Latin