Python抓取最新文件脚本运行后

时间:2018-02-06 13:13:04

标签: python flask

我正在编写一个数据解析脚本,数据每小时刷新一次。我有脚本工作,它从第一次运行脚本时抓取最近的文件。但是,如果在脚本当前正在运行时传递更新,则无法检测到新文件。当它在腻子中运行时,这不是一个问题,但我正在重新创建烧瓶中的所有东西。

def getLatestFile():
    import glob, os
    list_of_files = glob.glob('./Source/data.parsed*.txt')
    latest_file = max(list_of_files, key=os.path.getctime)
    return latest_file

if __name__ == '__main__':
    ###Creates a Dictionary from the latest Data File
    headers = None
    content = {}
    csvFile = getLatestFile()
    modTime = os.path.getmtime(csvFile)
    reader=csv.reader(open(csvFile), delimiter = '|') #opens File
    print('Creating Dictionary from file ' + csvFile + '\nLast modified date - ' + str(datetime.datetime.fromtimestamp(modTime)))
    for row in reader: # Writes data to dictionary
       if reader.line_num == 1:
           headers = row[1:] #grabs first row and creates headers
           print(headers)
       else:
           content[row[0]] = dict(zip(headers, row[1:])) #creates dictionary
    app.run(host=os.getenv('IP', '0.0.0.0'), port =int(os.getenv('PORT', 8080)), debug=True)

当我尝试使用下面的代码重新创建字典时,它只会从创建脚本时获取最新文件

def updateDict():
    headers = None
    content = {}
    csvFile = getLatestFile()
    modTime = os.path.getmtime(csvFile)
    for row in reader: # Writes data to dictionary
       if reader.line_num == 1:
           headers = row[1:] #grabs first row and creates headers
       else:
           content[row[0]] = dict(zip(headers, row[1:])) #creates dictionary

我尝试了latest_file = max(list_of_files, key=os.path.getmtime),但它仍然忽略了放入源目录的新文件。

1 个答案:

答案 0 :(得分:0)

latest_file = max(list_of_files, key=lambda x : max(os.path.getmtime(x),os.path.getctime(x))) 以奇怪的方式运作:

  

返回系统的ctime,在某些系统(如Unix)上是最后一次元数据更改的时间,而在其他系统(如Windows)上则是路径的创建时间。

因此,检测哪个文件是最后一个文件是好的,但不能检测是否已修改现有文件。

我建议更改密钥以计算创建时间和修改时间之间的最大值:

peter