Reputation: 69
I need to find a way to add a new line after a certain string within a text file.
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
Here I have a .txt file and I need a way to add a new line after any line containing 'original_price' and the price/ numbers after it.
there is probably an easy solution to this but I can't seem to figure this out, and I have practically 0 knowledge of how to use Regex
I have tried the following:
def fixSpacing():
file1 = open('data.txt', 'w')
file2 = open('tempdata.txt', 'r+')
for line in file2.readlines():
if line.startswith('original_price :'):
But I couldn't think of a way to add a new line after the numbers for price.
Upvotes: 3
Views: 297
Reputation: 36725
For me it looks like task for built-in module fileinput as it can work in inplace mode. Consider following example, let file.txt
content be:
title: 1
price: 100
desc: one
title: 2
price: 200
desc: two
then
import fileinput
for line in fileinput.input("file.txt", inplace=True):
end = "\n" if line.startswith("price") else ""
print(line, end=end)
will change said file content to
title: 1
price: 100
desc: one
title: 2
price: 200
desc: two
explanation: in inplace mode standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. so we can just use print
, as input file lines' newlines are preserved using \n
as print
's end
will result in additional empty line and empty str in keeping line unchanged. Keep in mind after using this you will no longer have original file, only altered.
Upvotes: 5
Reputation: 69
Thanks, I tinkered around with it for about 10 min and got it to work with the following:
def fixSpacing():
file1 = open('data.txt', 'w')
file2 = open('tempdata.txt', 'r+')
for line in file2.readlines():
if 'original_price' in line:
file1.writelines(line + '\n')
else:
file1.write(line)
Thanks for the Help.
Upvotes: 1