如何对多个文件使用 getmtime [英] How to use getmtime for multiple files
问题描述
我当前的python脚本:
My current python script:
import ftplib
import hashlib
import httplib
import pytz
from datetime import datetime
import urllib
from pytz import timezone
import os.path, time
import glob
def ftphttp():
ts = os.path.getmtime('Desktop/images/frame00.png')
dt = datetime.fromtimestamp(ts, pytz.utc)
timeZone= timezone('Asia/Singapore')
#converting the timestamp in ISOdatetime format
localtime = dt.astimezone(timeZone).isoformat()
cam = "002"
lscam = localtime + cam
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=hashlib.md5()
m.update(lscam)
dd=m.hexdigest()
for image in glob.glob(os.path.join('Desktop/images/frame**.png')):
with open(image, 'rb') as file:
ftp.storbinary('STOR '+dd+ '.png', file)
x = httplib.HTTPConnection('localhost', 8086)
x.connect()
f = {'ts' : localtime}
x.request('GET','/camera/store?cam='+cam+'&'+urllib.urlencode(f)+'&fn='+dd)
y = x.getresponse()
z=y.read()
x.close()
ftp.quit()
现在这行代码只得到一个文件时间戳:
As right now this line of code is only get one file timestamp:
ts = os.path.getmtime('Desktop/images/frame00.png').
但是如果我从一个文件夹发送多个文件并获取所有文件的时间戳怎么办.有可能做到吗?我使用 ftplib 将多个文件夹从一个文件夹发送到另一个文件夹.
But what if i send multiple file from a folder and get all the files timestamp. Is it possible to do it? I using ftplib to send multiple from a folder to another folder.
推荐答案
如果有问题的目录是 Desktop/images,您可以只遍历目录并获取该目录中所有文件的时间
You could just walk the directory and getmtime for all the files in that directory if the directory in question is Desktop/images
可以替换
ts = os.path.getmtime('Desktop/images/frame00.png')
dt = datetime.fromtimestamp(ts, pytz.utc)
类似于:
dirToCheck = 'Desktop/images'
for root, _, file in os.walk(dirToCheck):
fileToCheck = os.path.join(root, file)
ts = os.path.getmtime(fileToCheck)
dt = datetime.fromtimestamp(ts, pytz.utc)
print ts, dt
使用这种方法,您将需要提供图像目录的绝对路径,并且还可能将时间戳存储在带有文件 - 时间戳的列表或字典中.
With this approach you will need to give the absolute path to the images directory and also maybe store the timestampes in a list or dictionary with file - timestamp.
如果您只想为 png 执行此操作,您还可以添加如下一行:
If you want to do it for png only you can also add a line like:
if file.endswith(".png"):
在 fileToCheck 行之前.
before the fileToCheck line.
除非我误解了您的问题,否则应该这样做.
This should do it unless i misunderstood your question.
这篇关于如何对多个文件使用 getmtime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!