如何在文本文件中的某个字符串后添加一个空行?
我需要找到一种方法在文本文件中的某个字符串后添加新行。
discount_percent :20
discounted :true
final_price :1199
id :893850
name : THELONGING
original_price :1499
discount_percent :40
discounted :true
final_price :119
id :1476450
name : CyberHentai
original_price :199
discount_percent :30
discounted :true
final_price :139
id :1478030
name : MamboWave
original_price :199
discount_percent :15
discounted :true
final_price :84
id :1506230
name : BigfootForest
original_price :99
discount_percent :40
discounted :true
final_price :59
id :1502600
name : AlienX
original_price :99
这里我有一个 .txt 文件,我需要一种方法在任何包含“original_price”的行之后添加一个新行,以及它后面的价格/数字。
可能有一个简单的解决方案,但我似乎无法解决这个问题,而且我几乎对如何使用 Regex 的知识为 0
我尝试了以下方法:
def fixSpacing():
file1 = open('data.txt', 'w')
file2 = open('tempdata.txt', 'r+')
for line in file2.readlines():
if line.startswith('original_price :'):
但是我想不出在价格数字后添加新行的方法。
回答
对我来说,它看起来像是内置模块fileinput 的任务,因为它可以在就地模式下工作。考虑以下示例,让file.txt内容为:
title: 1
price: 100
desc: one
title: 2
price: 200
desc: two
然后
import fileinput
for line in fileinput.input("file.txt", inplace=True):
end = "n" if line.startswith("price") else ""
print(line, end=end)
将所述文件内容更改为
title: 1
price: 100
desc: one
title: 2
price: 200
desc: two
解释:在就地模式下,标准输出被定向到输入文件(如果与备份文件同名的文件已经存在,它将被静默替换)。这使得编写一个过滤器来重写其输入文件成为可能。因此,我们可以只使用print,如输入文件行换行符使用保存n为print的end会导致额外的空行,然后在保持线不变空海峡。请记住,使用此功能后,您将不再拥有原始文件,只有更改过。