python - 将文件复制到临时目录并在最后删除
问题描述
为了在 python 代码中使用临时目录,我正在对文件进行一些转换。从 yaml 生成 json ..想要将它们复制到临时目录,同时生成它们,最后还要 rm 。
解决方案
我认为这可以满足您在 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
如果你把所有的评论都拿出来,这里真的只有几行功能,为了方便使用,把它们分成功能
推荐阅读
- c# - 方法没有重载匹配委托'EventHandler'
- python-3.x - 当我尝试将 BGR 转换为 HSV 并得到错误 cvtColor 时出了什么问题?
- youtube - YouTube 和 Netflix 如何将内容推送到 Roku?
- node.js - Mongoose - 如何在 Mongoose 的填充字段数组中选择特定对象?
- chromecast - 创建自定义 CAF 接收器
- assembly - 为什么旋转槽的第一个和第二个图像永远不能相同?
- javascript - 如何从输入文件设置背景图像?
- ruby-on-rails - 通过 lang 获取 TMDB API
- ruby-on-rails - 带有 ActionMailer 和复杂活动记录的 Rails(连接、位置和)
- mongodb - 排序和过滤时查询慢