I am trying to write Python code that checks if indentation within a YAML file is indented correctly and flags an error if any inconsistencies exist.
For example, the second occurrence of the key-value pair mapping "class" has 4 spaces before it when it should instead have 6 spaces (like the first occurrence).
I have dozens of these YAML files with thousands of entries. So, I need an automated way to check if the indentation is inaccurate.
How could I achieve this within Python?
students:
incoming:
- enrolled: TRUE
semester: final
destination:
name:
- John Walsh
- Heather Dunbar
class:
- 1258
- enrolled: TRUE
semester: final
destination:
name:
- Alfred Flynn
- Joe Diaz
class: ## incorrectly indented entry.
- 3662
Here's my code:
class_indentation = " class:"
with open("yamls/students.yaml", "r") as file:
for line_number, line in enumerate(file, start=1):
if class_indentation in line:
print(f"Indentation for '{class_indentation}' is valid: {line_number}")
break
else:
print(f"Indentation for '{class_indentation}' is NOT valid: {line_number}")
print("Search completed.")