python - 从正在写入python的文件夹中读取文件
问题描述
我有一个不断写入文件的文件夹(来自 Raspberry Pi)。我想运行一个 Python 代码,它将从同一个文件夹中读取文件(并处理它们)。在将 5 个文件写入文件夹后,我启动 Python 代码。但随后代码在处理了 5 个文件后停止。关于如何将文件从这个动态更新的文件夹“流式传输”到我的 Python 代码中的任何建议?
谢谢
我正在使用以下代码,想知道是否还有其他解决方案:
import os
import time
import numpy as np
from PIL import Image
import datetime
# get the data & time of an image output is str with format '%Y:%m:%d
%H:%M:%S'
def get_date_taken(path):
return Image.open(path)._getexif()[36867]
# get the difference in time between two images in seconds
def getTimeDiffBetwImages(path1,path2):
a1 = get_date_taken(path1)
a2 = get_date_taken(path2)
b1 = datetime.datetime.strptime(a1,'%Y:%m:%d %H:%M:%S')
b2 = datetime.datetime.strptime(a2,'%Y:%m:%d %H:%M:%S')
return (b1-b2).total_seconds()
def getDiffImgs(img1,img2):
a = img1.shape
diff = np.zeros((a[0],a[1],a[2]),dtype = "uint8")
for i in range(0,a[0]):
for j in range(0,a[1]):
for k in range(0,a[2]):
diff[i,j,k] = abs(int(img2[i,j,k]) - int(img1[i,j,k]))
return diff
folder = "D:/work"
file_num = 0
img_prev = []
last_file = None
while True:
for f in os.listdir(folder):
path1 = os.path.join(folder,f)
if not(last_file == None):
path2 = os.path.join(folder,last_file)
time_diff = getTimeDiffBetwImages(path1,path2)
else:
time_diff = 0
if time_diff >= 0:
print(f)
im = cv2.imread(os.path.join(folder,f))
img_curr = np.copy(im)
fname = "Diff_" + f
if file_num > 0:
diff = getDiffImgs(img_prev,img_curr)
cv2.imwrite(fname,diff)
img_prev = np.copy(img_curr)
file_num += 1
time.sleep(10) # additional processing but just delay out here
last_file = f
解决方案
如果您在添加 5 个文件时正在读取该文件夹。它可能只保留这五个文件的日志。添加的任何新文件都不会反映。我认为一个好的解决方案是将一组文件添加到目录中。在处理集合中的文件时,如果最后一个文件出现,您可以再次检查目录中是否有任何新文件并将它们添加到该集合中。保持循环,直到不满足您的首选条件。
我希望它有所帮助。谢谢。
推荐阅读
- grid - 3d 中的 Ue4 TiledMap 生成
- python - 读取本地状态/检查点值 Pulumi
- python - python dataframe drop().index 混淆
- openflow - 使用 openflow 拒绝(而不是!只是丢弃)数据包
- angular - Angular 中带有 CustomWeback 的 ImageminPlugin 在生产环境中不起作用
- signal-processing - 在一个 SPI 端口和一个片选上连接 DSP 与 ADC 和 DAC 数据转换器
- php - 如何删除最后一页使用 PHP 的历史记录?
- php - 使用 PHP Imagick 将 ICO 转换为 PNG
- django - 如何在我的 Django Modelform 中进行自定义验证?
- php - Apache 2,PHP - HTTP GET 域上的问题