gpt4 book ai didi

python - 如何在文本文件中的某个字符串后添加一个空行?

转载 作者:行者123 更新时间:2023-12-04 00:52:19 26 4
gpt4 key购买 nike

我需要找到一种方法在文本文件中的某个字符串之后添加一个新行。

 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 保留了输入文件行的换行符作为printend将导致额外的空行和空 str 以保持行不变。请记住,使用此功能后,您将不再拥有原始文件,只有更改。

关于python - 如何在文本文件中的某个字符串后添加一个空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65640106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com