python - Python,创建时复制文件
问题描述
我正在 Python 上编写用于复制 cron 配置的脚本。我需要将我的文件复制到/etc/cron.d/
,如果目标文件不存在,则必须创建它。我找到了解决方案,但它没有提供丢失的文件,这里是:
from shutil import copyfile
def index():
src = "/opt/stat/stat_cron"
dst = "/etc/cron.d/stat_cron"
copyfile(src, dst)
if __name__ == "__main__":
index()
我得到异常"FileNotFoundError: [Errno 2] No such file or directory: '/etc/cron.d/stat_cron'"
请告诉我正确的解决方案。
解决方案
from pathlib import Path
def index():
src = "/opt/stat/stat_cron"
dst = "/etc/cron.d/stat_cron"
my_file = Path(dst)
try:
copyfile(src, dest)
except IOError as e:
my_file.touch() #create file
copyfile(src, dst)
使用 pathlib 检查文件是否存在,如果不存在则创建文件。
推荐阅读
- c# - 如何避免在 MVC 架构中的 post 方法之后再次获取模型数据?
- django - 如何通过邮递员将发布请求发送到 django-rest-framework 中的嵌套可写序列化程序?
- c - 使用 SIMD 和 openMP 加速矩阵乘法
- go - 如何在 Go 中创建递归并发树搜索
- flutter - 匹配导航器小部件中的子高度大小
- web-component - stenciljs webcomponents : 用于简单分步向导的离子路由器?
- svelte - 无法安装 Sveltejs
- c - 在 SDL2 中处理多个图像
- c# - 删除具有相同属性的列表
- ios - 如何约束视图以保持其固有宽度但使其保持在右侧