【轉】Linux下同時復制多個文件


一、命令方法

1.使用cp命令

cp /home/usr/dir/{file1,file2,file3,file4} /home/usr/destination/

需要注意的是這幾個文件之間不要有空格

2.具有共同前綴

cp /home/usr/dir/file{1..4} ./

復制的文件是file1, file2, file3, file4

 

二、腳本方法

使用python腳本 shutil庫

import os,sys,shutil
### copies a list of files from source. handles duplicates.
def rename(file_name, dst, num=1):
    #splits file name to add number distinction
    (file_prefix, exstension) = os.path.splitext(file_name)
    renamed = "%s(%d)%s" % (file_prefix,num,exstension)

    #checks if renamed file exists. Renames file if it does exist.
    if os.path.exists(dst + renamed):
        return rename(file_name, dst, num + 1)
    else:
        return renamed

def copy_files(src,dst,file_list):
    for files in file_list:
        src_file_path = src + files
        dst_file_path = dst + files
        if os.path.exists(dst_file_path):
            new_file_name =  rename(files, dst)
            dst_file_path = dst + new_file_name

        print "Copying: " + dst_file_path
        try:
            # 復制操作主要就是這句
            shutil.copyfile(src_file_path,dst_file_path)
        except IOError:
            print src_file_path + " does not exist"
            raw_input("Please, press enter to continue.")

def read_file(file_name):
    f = open(file_name)
    #reads each line of file (f), strips out extra whitespace and 
    #returns list with each line of the file being an element of the list
    content = [x.strip() for x in f.readlines()]
    f.close()
    return content

src = sys.argv[1]
dst = sys.argv[2]
file_with_list = sys.argv[3]

copy_files(src,dst,read_file(file_with_list))

2. 將以上代碼保存為move.py

3. 運行 $ python move.py /path/to/src/ /path/to/dst/ file.txt
4. file.txt 中定義要復制的文件名字,只要給出名字即可,不需要路徑

 

轉自:https://www.cnblogs.com/zhonghuasong/p/7352758.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM