Python-copy files and folders to the specified folder

Requirements - Copy files and folders to specified folders

I used the windows batch command before, but I felt that the syntax was too unfriendly, and a lot of parameters needed to be passed, which was cumbersome to use, so I finally implemented it with Python.

EnvironmentPython3

the code

#_*_coding:utf-8_*_

import os  # os是用来切换路径和创建文件夹的。
import shutil
import time

FromRoot = r"D:\hahaha"  #硬盘路径 来源路径
ToRoot = r"D:\newbee"  #硬盘路径   目标路径 别人使用的时候 修改这俩个就好

file_path1 = FromRoot+ r'\xx\file1.jar'  #第一个文件的来源
file_to1 = ToRoot+ r'\xx\file1.jar'  #需要拷贝的地方  这些都是文件路径

file_path2 = FromRoot+ r'\xx\File2' 
file_to2 = ToRoot+ r'\xx\File2'

file_path3 = FromRoot+ r'\xx\File3'
file_to3 = ToRoot+ r'\xx\File3'



if __name__ == '__main__':
    if os.path.exists(file_to1):
        print(file_to1)
        os.remove(file_to1)
    if os.path.exists(file_to2):
        # print(file_to2)
        shutil.rmtree(file_to2)
    if os.path.exists(file_to3):
        # print(file_to3)
        shutil.rmtree(file_to3)
    time.sleep(1)
    shutil.copyfile(file_path1,file_to1)
    shutil.copytree(file_path2,file_to2)
    shutil.copytree(file_path3, file_to3)
    print("拷贝成功")
    # os.system("pause")

run successfully, end

Too many tutorials on the Internet are really incomprehensible and a bit too troublesome. I delete them before copying, and I don’t bother to judge.

The Shutil module is mainly used here

shutil.copyfile, as the name implies, copies files

shutil.copytree, as the name implies, copies folders

This is used because I clearly know that they are files and folders, and you can modify them according to your needs.

PS: In order to improve the effect, it can be used with bat

After the script is written, it can be used with bat, so that you don’t need to open the command line every time, create a new notepad, and then enter the command

echo 开始拷贝
py .\xx.py
pause

Then modify the suffix bat of Notepad, and double-click the bat for later use, which can improve efficiency

reference

Guess you like

Origin blog.csdn.net/h824612113/article/details/127921746