Python,通过创建复制文件

2024-04-23 14:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Python上为copy cron config编写脚本。我需要将文件复制到/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'"

请告诉我正确的解决方法。你知道吗


Tags: 文件fromsrc脚本config目标indexetc
3条回答

谢谢大家。成功解决了下一个问题:

out_file_exists = os.path.isfile(dst)
out_dir_exists = os.path.isdir("/etc/cron.d")

if out_dir_exists is False:
    os.mkdir("/etc/cron.d")

if out_file_exists is False:
    open(dst, "a").close()
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检查文件是否存在,如果不存在,则创建一个文件。你知道吗

如果文件存在,使用os.makedirs可以帮助检查条件,如果不存在,则创建一个

from shutil import copyfile
import os

def index():
    src = "/opt/stat/stat_cron"
    dst = "/etc/cron.d/stat_cron"
    os.makedirs(dst,exit_ok=True)
    copyfile(src, dst)


if __name__ == "__main__":
    index()

相关问题 更多 >