如何只移动新文件或已更新文件?

2024-09-30 07:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个脚本,将只移动新的或更新的文件从过去的24小时到一个新的文件夹。我创建了一个脚本,到目前为止,将移动一般的文件,任何线索或建议将不胜感激。你知道吗

import os, shutil

source = os.listdir('C:\Users\Student\Desktop\FolderA')
destination = 'C:\Users\Student\Desktop\FolderB'

os.chdir('C:\Users\Student\Desktop\FolderA')

for files in os.listdir("C:\Users\Student\Desktop\FolderA"):
    if files.endswith(".txt"):
        src = os.path.join("C:\Users\Student\Desktop\FolderA",files)
        dst = os.path.join(destination,files)
        shutil.move(src,dst)

Tags: 文件pathsrc脚本osfilesdestinationusers
1条回答
网友
1楼 · 发布于 2024-09-30 07:24:33

我相信我找到了解决办法,让我知道你们的想法。你知道吗

# copy files from folder_a to folder_b
# if the files in folder_a have been modified within the past 24 hours
#   copy them to folder_b
#


import shutil
import os
from os import path
import datetime
from datetime import date, time, timedelta


def file_has_changed(fname):
#  print 'in file_has_changed with file : %s' % fname
#  print str(path.getmtime(fname))

# get file modified time
  file_m_time = datetime.datetime.fromtimestamp(path.getmtime(fname))

#  print datetime.datetime.now()
#  print file_m_time

  #get the delta between today and filed mod time
  td = datetime.datetime.now() - file_m_time

#  print td
#  print 'days : %d' % td.days

 # file can be archived if mod within last 24 hours
  if td.days == 0:
    global ready_to_archive
    ready_to_archive = ready_to_archive + 1
    return True
  else: return False



def main():
  global ready_to_archive
  global archived
  ready_to_archive, archived = 0, 0

  # src = "c:\users\gail\desktop\foldera"
  # dst = "c:\users\gail\desktop\folderb"

  for fname in os.listdir('c:\users\gail\Desktop\FolderA'):

    src_fname = 'c:\users\gail\Desktop\FolderA\%s' % fname

    if file_has_changed(src_fname):    
      dst_fname = 'c:\users\gail\Desktop\FolderB\%s' % fname
      dst_folder = 'c:\users\gail\Desktop\FolderB'


      try:
        shutil.copy2(src_fname, dst_folder)
        global archived;
        archived = archived + 1
      #  print 'Copying file : %s ' % (src_fname)
      #  print '      To loc : %s ' % (dst_fname)
      except IOError as e:
        print 'could not open the file: %s ' % e



if __name__ == "__main__":

  main()

  print '******   Archive Report for %s   ******' % datetime.datetime.now()
  print '%d files ready for archiving ' % ready_to_archive
  print '%d files archived' % archived
  print '******   End of Archive Report   ******'

相关问题 更多 >

    热门问题