首页 > 解决方案 > 将文件复制到临时目录并在最后删除

问题描述

为了在 python 代码中使用临时目录,我正在对文件进行一些转换。从 yaml 生成 json ..想要将它们复制到临时目录,同时生成它们,最后还要 rm 。

标签: pythonjson

解决方案


我认为这可以满足您在 python 中可能需要的所有内容,并且没有临时文件。这将为目录中的每个 yaml 文件创建一个包含 yaml 数据的 json 文件。如果你需要对从 yaml 加载的字典做更多的处理,你可以通过组合这些函数来非常容易地做到这一点:

import os
import glob
import json
import yaml

def jsonify(data):
    print(json.dumps(data, indent=4)) # print pretty json formatted for debugging and examples

def open_yaml(path):
    with open(path, 'r') as file:
        return yaml.load(file, Loader=yaml.BaseLoader) # load objects as strings so they work with json

def write_json(path, data):
    with open(path, 'w') as file:
        file.write(json.dumps(data, indent=4)) # remove indent arg for minified

def file_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 extension

def get_all_files(path, ext='.yaml'):
    return glob.glob(os.path.join(path, f'*{ext}')) # find with files matching extension

def dir_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

如果你把所有的评论都拿出来,这里真的只有几行功能,为了方便使用,把它们分成功能


推荐阅读