首页 > 解决方案 > 如何将文件从一个目录移动到另一个目录?

问题描述

目录文件名应附加当前日期 (yyyy-mm-dd)

import shutil
import os

source = '/path/to/source_folder'
dest1 = '/path/to/dest_folder'

files = os.listdir(source)

for f in files:
        shutil.move(source+f, dest1)

标签: pythonpython-3.xfileunixfile-copying

解决方案


这可能对您有所帮助。

 import os
 import datetime
 import shutil
 now = datetime.datetime.now()

 path  ='f:\\python\\testdir\\'
 dest_folder='f:/python/testdir/copyfolder/'

 files=[]
 #check if destination folder exists if not create one
 if os.path.exists(dest_folder):
    #ignore nothing to do
    pass
 else:
   print("not exits")
   os.mkdir(dest_folder)
 for r, d, f in os.walk(path):
   for file in f:
      # if '.txt' in file:
         #print(os.path.join(r, file))
         files.append(os.path.join(r, file))
 for f in files:
    print(f)
    #extract the file name from the path
    base_name=os.path.basename(f)

    #extracting the file name and it's extension 
    file_name,ext=os.path.splitext(base_name)

    #print(ext)
    #file_name+='_'+now.strftime("%Y-%m-%d %H:%M")

    #append the current time stamp and it's extension and move the file to new destination
     shutil.copy2(f,'f:/python/testdir/copyfolder/'+file_name+'-'+now.strftime("%Y-%m-%d")+ext)

    #print(file_name)

推荐阅读