Find files/folders that are modified after a specific date in Python

风格不统一 提交于 2019-12-25 05:01:30

问题


Problem ; find files/folders that are changed after a specific date from a directory structure and copy these to another location (as stated clearly in title as well) (:

By the following ;

def mod():
     """Find files modified today, given a file path."""
     latest = 0
     now = time.strftime('%Y-%m-%d', time.localtime())
     dir = "/home/y33t/"
     for fname in os.listdir(dir):
         if fname.endswith(''):
             modtime = os.stat(os.path.join(dir, fname)).st_mtime
             if modtime > latest:
                 latest = modtime
                 out = time.strftime('%Y-%m-%d', time.localtime(latest))
                 if out == now:
                     print fname, "has changed today. "
                 else:
                     pass

I can determine which files are changed at a specific date and copy these to a location. What I would like to achieve is to keep the directory structure as well. An example is as following ;

/testfolder
..somefile1
..somefile2
../testfolder2
....somefile3
....somefile4

and so on...

lets say somefile3 is changed at the specified date and I will save it to another location but while saving, cascaded directory structure should be maintained as well. How can I achieve this in an elegant way ?


回答1:


Before copying, you should solve reading. os.listdir will give you only one level while os.walk will let you go over each file in every depth.

To copy, you will first use os.makedirs(target-path) to create all the folders from root to target folder at any depth then you will use shutil.copy to copy the file.



来源:https://stackoverflow.com/questions/11259273/find-files-folders-that-are-modified-after-a-specific-date-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!