Search code examples
pythondataframeyamlpyyaml

Dumping data to existing yaml file with yaml code inside


I'm dumping some data from an .csv file to .yml file using yaml.dump. My problem is that when i dump data to the .yml file. All the current yaml iside of it vanishes and only the new yaml from the .csv file shows.

Examples:

Before I dump yaml to .yml file:

Text: 'This is some yaml'
MoreText: 'This is more yaml'

After I dump yaml (All the current yaml vanihes and only the new shows):

NewYamlFromCsvFile: 'This is new yaml'

What I want:

Text: 'This is some yaml'
MoreText: 'This is more yaml'
NewYamlFromCsvFile: 'This is new yaml'

Here's my yaml.dump code:

            yaml.dump(
            df.loc[(df['NAME'] == pack)].to_dict(orient='records'), # Send keywords to the right pack, etc java keywords to java pack.
            outfile,
            sort_keys=False,
            width=72, 
            indent=4
        )

I there any way to not delete the current yaml when new yaml is dumped? Thanks!


Solution

  • You should open the output file in 'a' mode (append mode):

    with open('output.yml', 'a') as outfile:
           yaml.dump(your_data, outfile, other_args )