Reputation: 99
I have a bunch of YAML files and each file has one line of code that needs to be changed. I am trying to automate it using Python, what's the best way to do this?
Right now I have a list of the files, and I plan on opening each one and finding the line needed to be changed then replacing it.
Is this possible? I can't seem to figure out how to replace the line. I know the exact line number, could that help?
Upvotes: 0
Views: 3258
Reputation: 1456
I use the pyyaml library (pip install pyyaml
):
It handles the full YAML syntax as shown in the example below:
python example
import yaml
with open("data.yaml", "w+") as FILE:
data = yaml.load(FILE)
data.pop("token_default")
yaml.dump(data)
data.yaml
token_default: &token
token : !!str
type : # var, field, list, vector
version : 0.1
namespace : cam_tokens
properties :
unit : !!seq [0, 0, 0, 0, 0, 0]
min : !!float +inf
max : !!float -inf
argPos : !!int -1
required :
- unit
- argPos
mass:
<<: *token
token: mass
namespace : cam_tokens
properties :
unit : !!seq [1, 0, 0, 0, 0, 0]
required :
- unit
- argPos
Upvotes: 0
Reputation: 357
Since you know the exact line number, this is quite easy - it doesn't even matter that the file is YAML if you know exactly what you need to replace it with.
I'm assuming here that all the files that need their lines changed are in the same directory, with no other YAML files. If this isn't the case then the program will require fine-tuning of course.
import os
line_number = 47 # Whatever the line number you're trying to replace is
replacement_line = "Whatever string you're replacing this line with"
items = os.listdir(".") # Gets all the files & directories in the folder containing the script
for file_name in items: # For each of these files and directories,
if file_name.lower().endswith(".yaml"): # check if the file is a YAML. If it is:
with open(file_name, "w") as file: # Safely open the file
data = file.read() # Read its contents
data[line_number] = replacement_line # Replace the line
file.write(data) # And save the file
Note that if your files are .yml rather than .yaml, then you would have to change that in the code. Additionally, if your files are too large this could cause problems as each file is loaded into memory.
If this doesn't work for you, then there are other solutions around the internet, including Stack Overflow!
Upvotes: 1