简体   繁体   中英

Python, copy file with creation

I'm writing script on Python for copy cron config. I need to copy my file to /etc/cron.d/ , and if destination file isn't exist it must be created. I found solution, but it doesn't provide missing file, here it is:

from shutil import copyfile


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


if __name__ == "__main__":
    index()

I get exception "FileNotFoundError: [Errno 2] No such file or directory: '/etc/cron.d/stat_cron'"

Please, tell me correct solution.

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)

Use pathlib to check if file exists and create a file if not.

using os.makedirs can help to check the condition if file exist and create one if not

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()

everybody thanks. success solved issue with next coditions:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM