Python,通过创建复制文件

时间:2019-02-18 07:54:13

标签: python file copy

我正在Python上为复制cron配置编写脚本。我需要将文件复制到<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <textarea id="text" class="form-control" name="text" cols="55" rows="5" placeholder="Description"></textarea> <br/> <input type="text" class="equipment" placeholder="Enter text to search"/> <input type="button" id="clear" value="Clear"/> <input type="button" id="fill" value="Fill"/> <script> $(document).ready(function(){ $("#clear").click(function(){ $( "#text" ).html( "" ); }); $("#fill").click(function(){ $( "#text" ).html( "X" ); }); var equipment = [ "ActionScript", "Asp", "BASIC", "C", "C++", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "Scala", "Scheme" ]; $( ".equipment" ).autocomplete({ source: equipment, select: function( event, ui ) { $( "#text" ).html( ui.item.label); return true; } }); }); </script>,如果目标文件不存在,则必须创建它。我找到了解决方法,但是它不提供丢失的文件,这里是:

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

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

3 个答案:

答案 0 :(得分:1)

import java.awt.FlowLayout;
import java.io.FileNotFoundException;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class ComboBox extends JFrame {

    public ComboBox() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 300);
        setLocationRelativeTo(null);
        getContentPane().setLayout(new FlowLayout());
        Integer[] numbers = { 4, 5, 8, 123, 42, 634 };
        JComboBox<Integer> comboBox = new JComboBox<>(numbers);
        comboBox.setSelectedItem(42); // The initial selection is 42.
        comboBox.addActionListener(e -> {
            int selectedNumber = (int) comboBox.getSelectedItem();
            System.out.println("Selected number: " + selectedNumber);
            // Do whatever with selected number
        });
        add(comboBox);
    }

    public static void main(String[] args) throws FileNotFoundException {
        SwingUtilities.invokeLater(() -> new ComboBox().setVisible(true));
    }

}

使用pathlib检查文件是否存在,如果不存在则创建文件。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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