Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,通过创建复制文件_Python_File_Copy - Fatal编程技术网

Python,通过创建复制文件

Python,通过创建复制文件,python,file,copy,Python,File,Copy,我正在用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__":

我正在用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]没有这样的文件或目录:'/etc/cron.d/stat\u 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检查文件是否存在,如果不存在,则创建一个文件。

使用操作系统。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()

谢谢大家。成功解决了与下一个条件有关的问题:

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

提示:检查特定文件是否存在于
copy()
之前,如果不存在,则创建它。PS.压痕不良。