I have a file which has multiple instances of "position": [num, num] (num is a random number).
Now I want to replace those instances with "position": [num, num, 0], so basically just add a , 0 after the two numbers. But how can I do that?
I tried doing text.replace('"position": [%d, %d]', '"position": [%d, %d, 0]'). That didn't work though.
CodePudding user response:
You can use the following re.sub to do the replacements (demo).
Edit for OP's comments:
Given that the file is fairly small, I'd iterate through it while reading, applying the substitution as I go, and then dump all the subbed lines into the same location.
import re
file_path = "/tmp/74987707.txt" # substitute your own
output_lines = []
with open(file_path, mode="rt") as f:
for line in f:
subbed_line = re.sub(
r'("position": \[\d (?:\.?\d*), \d (?:\.?\d*))(])',
r'\1, 0\2',
line
)
output_lines.append(subbed_line)
with open(file_path, mode="wt") as f:
f.writelines(output_lines)
Regex explanation:
- group 1
("position": \[\d (?:\.?\d*), \d (?:\.?\d*))
(start"position": \[match exactly (escaping[)\dmatch one or more digit(?:\.?\d*)non capturing group, match a possible literal dot.and one or more digits,match exactly\d (?:\.?\d*)see above)end
- group 2
(\])
(start\]match exactly (escaping]))end
CodePudding user response:
From the structure of what you posted it looks like a json file, you can just loop through the items and append 0
import json
with open('example.json', 'r') as f:
data = json.load(f)
for item in data:
if 'position' in item:
if isinstance(item['position'], list) and len(item['position']) == 2:
item['position'].append(0)
with open('example_modified.json', 'w') as f:
json.dump(data, f)
