Ivan S
Ivan S

Reputation: 95

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.

Upvotes: 1

Views: 86

Answers (3)

Ivan S
Ivan S

Reputation: 95

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

Upvotes: 0

sahasrara62
sahasrara62

Reputation: 11228

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

Upvotes: 1

Nihal Sangeeth
Nihal Sangeeth

Reputation: 5515

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.

Upvotes: 1

Related Questions