BrownBatman
BrownBatman

Reputation: 199

How to write text file into yaml file with exact identation and formatting in python

I have a text file with indentation and I want that txt file to be converted into YAML with exact ideation.

Below is my text file by name Source.txt

source:
    dialect:sql
    host:RATDegeggPRD
    user:454the6yht
    pass:4fghrthrthrt6h
    auth:ldap
    database: "rvvrrf"
    queries: ["wrfrfrgvrv.sql"]
    autoInfer: true
    rows: -1

target:
    database: "ddfcvdss"
    schema: "dev"
    queryTables: ["vrvrfre"]

mode: "write"
logfile: "rttcfdwee.log"

Now I want this file but in YAML format with exact idenation.

below is what I tried to do

from pathlib import Path
import yaml

src_yaml = open("Source.txt", "r")
yaml_source = src_yaml.read()
in_file = Path('Source.txt')
out_file = in_file.with_suffix('.yaml')
yaml.dump(yaml_source, out_file)

Now, this code is generating a YAML file with all "\n" in between. Adding my sample output below

"source:\n\tdialect:teradata\n\thost:RATDegeggPRD\n\tuser:454the6yht\n\tpass:4fghrthrthrt6h\n\
\tauth:ldap\n  database: \"SCMAIN_V\"\n  queries: [\"vrervvrec.sql\"\
]\n  autoInfer: true\n  rows: -1\n\ntarget:\n  database: \"vrerevr\"\n  schema: \"\
dev\"\n  queryTables: [\"vrrrev\"]\n\nmode: \"write\"\nlogfile:\
\ \"fsefsfds.log\"\n"

I don't want all these \n or things like that. I want the exact indentation

Upvotes: 0

Views: 2178

Answers (1)

aminuolawale
aminuolawale

Reputation: 26

with open("source.txt", "r") as source, open("dest.yml", "wb") as dest:
    dest.write(source.read())

That worked for me.

Upvotes: 1

Related Questions