Replace numbers in YAML file with random numbers

Question:

I have a file with much numbers. I want that every number will be replaced with a random number. So that the Python script changes the YAML file. How to code this in Python?

!h 1: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 2: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 3: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 4: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 5: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
!h 6: {X: '-950,00000', Y: '1500,00000', Z: '150,00000'}
Asked By: customswitch

||

Answers:

You can do that with ruamel.yaml. There are various ways of generating random numbers, since you need them as scalar strings with a comma as decimal separator, I suggest using random.randrange and manipulating the result as a string:

import sys
from random import randrange
from pathlib import Path
import ruamel.yaml

in_file = Path('input.yaml')
out_file = Path('output.yaml')

def randfloatstr():
    # this gives you max 4 digits before the comma and 5 digits after
    x = str(randrange(0, 1000000000))
    return x[:-5] + ',' + x[-5:]
    
yaml = ruamel.yaml.YAML()
data = yaml.load(in_file)
for v in data.values():
    for k in v:
        v[k] = randfloatstr()

yaml.dump(data, out_file)
sys.stdout.write(out_file.read_text())

which gives:

!h 1: {X: '2767,85747', Y: '8281,59187', Z: '2729,91875'}
!h 2: {X: '324,84623', Y: '6669,00402', Z: '6183,89608'}
!h 3: {X: '5349,15868', Y: '7987,69554', Z: '243,05155'}
!h 4: {X: '6738,35201', Y: '2497,61750', Z: '2933,25689'}
!h 5: {X: '6013,68067', Y: '5265,31446', Z: '9229,21356'}
!h 6: {X: '4656,47702', Y: '4710,97938', Z: '5264,45726'}

ruamel.yaml will preserve the tags (!h), but cannot align the columns for smaller numbers.

Answered By: Anthon
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.