开发者

Python "if modified since" detection?

I wrote some code to tackle a work-related problem. The idea is that the program is in an infinite loop and every 10 minutes it checks a certain folder for new files and if there are any, it copies them to another folder. My code reads all the files in the folder and drops the list into a txt file. After 10 minutes it checks the folder again and compares the old list with a new list. If they are identical, it doesn't do anything. This is where I stopped, because my idea is iffy and stupid and started to think of better ways. Here's the code

import time
import os, os.path
i=1
while i==1:    
    folder="folderlocation"
    def getfiles(dirpat):
        filelist = [s for s in os.listdir(dirpat)
             if os.path.isfile(os.path.join(dirpat, s))]
        filelist.sort(key=lambda s: os.path.getmtime(os.path.join(dirpat, s)))
        return filelist
    newlist=getfiles(folder)
    outfile='c://old.txt'      
    last=newlist
    text_file = open(outfile, "r")
    oldlist = text_file.read()
    text_file.close()
    if str(last) == str(oldlist):
        i==i
        print "s"
    else:
        with open(outfile, 'w') as fileHandle:
       #this part is virtually useless
            diff=list(set(lines) - set(last))
            print diff
            fileHandle.write(str(getfiles(folder)))           
    time.sleep(600)

This realization has some bugs in it and doesn't work as I would like to. Is there another way of tackling it. Is it possible for it to just remember the latest modified date and after 10 minutes there are files that are newer, then it points开发者_StackOverflow them out? Don't need the copying part just yet but really need the checking part. Does anyone have some ideas or some similar code?


The cleanest solution is file alteration monitoring. See this question for information for both *ix and Windows. To summarize, on Linux, you could use libfam, and Windows has FindFirstChangeNotification and related functions.

There are some clear problems with your script, such as NOP lines like i==i. You also don't need to convert to a string before comparing.


A technique I've been using (I was actually working on generalising it two hours ago) keeps a {path: os.stat(path).st_mtime} dict, polling in a while True loop with time.sleep and updating the entries and checking if they've changed. Simple and cross-platform.


Another option for solving this problem would be to run rsync periodically, for example from cron.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜