首页 > 解决方案 > 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'"

请告诉我正确的解决方案。

标签: pythonfilecopy

解决方案


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 检查文件是否存在,如果不存在则创建文件。


推荐阅读