Skip to content Skip to sidebar Skip to footer

Copy Files To Temp Directory And Delete Those At The End

Looking to use temp directory in python code, I'm doing some transformations on the files. generating json from yaml..want to copy those to temp directory while generating those an

Solution 1:

I think this does what you may need all from within python and no temp files. This will create a json file with yaml data for each yaml file in a directory. If you need to do more processing to the loaded dictionary from yaml, you can do that too pretty easy by combining these functions:

import os
import glob
import json
import yaml

defjsonify(data):
    print(json.dumps(data, indent=4)) # print pretty json formatted for debugging and examplesdefopen_yaml(path):
    withopen(path, 'r') as file:
        return yaml.load(file, Loader=yaml.BaseLoader) # load objects as strings so they work with jsondefwrite_json(path, data):
    withopen(path, 'w') as file:
        file.write(json.dumps(data, indent=4)) # remove indent arg for minifieddeffile_yaml2json(path, ext='.yaml'):
    data = open_yaml(path) # dictionary of the yaml data
    write_json(path.replace(ext, '.json'), data) # write new file with new extensiondefget_all_files(path, ext='.yaml'):
    return glob.glob(os.path.join(path, f'*{ext}')) # find with files matching extensiondefdir_yaml2json(path, ext='.yaml'): # default to find .yaml but you can specify
    files = get_all_files(path)
    for file in files:
        file_yaml2json(file) # run for each detected yaml file

dir_yaml2json('./') # convert all the files in the current directory

If you take out all the comments there are really only a few functional lines here, just split them up in functions for ease of use

Post a Comment for "Copy Files To Temp Directory And Delete Those At The End"