python讀取更新中的文件夾/文件

最近做的項目需要讀取更新中的.log file.

也就是說,.log file在不斷增加內容,同時放置.log file的文件夾也在不斷增加.log file的數量,當一個.log file內存滿了之後,就會產生一個新的.log file.

所以我要做的兩件事就是:1. 如何讀取更新中的文件;2. 如何讀取更新中的文件夾

1. 讀取更新中的文件

加了一個start_point

它會記錄上一次讀取的位置,在下一次讀取的時候就從上一次讀取的位置開始讀取。

fo = open("C:\WinUSR" + "\\" + f_name, "rb")
start_point = 0  #設置初始指針爲0
fo.seek(start_point, 1)
for line in fo.readlines():
    line = str(line.decode('ISO-8859-1'))
    if fnmatch.fnmatch(line.lower(), "*error:*"):
        if fnmatch.fnmatch(line.lower(), "*secondary error 59*") or fnmatch.fnmatch(line.lower(), "*secondary error 450*"):
            try:
                errname = line[line.index(" ", line.index("TID-")) + 1:].strip()
                errtime =datetime.strptime(datetime.fromtimestamp(os.path.getmtime("C:\WinUSR" + "\\" + f_name)).strftime("%d-%b-%Y") + " " + line[:8], "%d-%b-%Y %H:%M:%S")

            except:
                continue
start_point = fo.tell() #記錄當前讀取的位置
fo.close()

2. 讀取更新中的文件夾

python沒有現成的功能可以實現,我採用的方法是當讀取完一個.log file之後把讀取完的這個file移動到另一個backup文件夾,然後重新掃描要讀取的文件夾。

    if os.path.exists("C:\WinUSR"):
        os.chdir("C:\WinUSR")
        while os.listdir("C:\WinUSR"): #由for循環改成了while循環,判斷文件夾是否爲空
            files = sorted(filter(os.path.isfile, os.listdir(".")), key=os.path.getmtime, reverse=True)
            for f_name in files:
                if fnmatch.fnmatch(f_name.lower(), "*.log"):
                    fo = open("C:\WinUSR" + "\\" + f_name, "rb")
                    start_point = 0
                    fo.seek(start_point, 1)
                    abort_time = datetime(1900, 1, 1)
                    errtime = datetime(1900, 1, 1)
                    errname = "No Errors"
                    for line in fo.readlines():
                        line = str(line.decode('ISO-8859-1'))
                        if fnmatch.fnmatch(line.lower(), "*error:*"):
                            if fnmatch.fnmatch(line.lower(), "*secondary error 59*") or fnmatch.fnmatch(line.lower(), "*secondary error 450*"):
                                try:
                                    errname = line[line.index(" ", line.index("TID-")) + 1:].strip()
                                    errtime = datetime.strptime(
                                        datetime.fromtimestamp(os.path.getmtime("C:\WinUSR" + "\\" + f_name)).strftime(
                                            "%d-%b-%Y") + " " + line[:8], "%d-%b-%Y %H:%M:%S")
                                    GUI()
                                except:
                                    continue
                    start_point = fo.tell()
                    fo.close()
                    shutil.move("C:\WinUSR" + "\\" + f_name, "C:\wintrace_backup") #移動已經讀取的文件到新的位置
    return

這個方法需要建立新的文件夾保存已經讀取的文件,不是很理想的方法。接下來會探索其他的方法,如果小夥伴有其他的方法歡迎和我分享謝謝!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章