今天就跟大家聊聊有关怎么在python中根据日期对文件进行归档,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
import os
import datetime
import shutil
# get file name
def get_datetime(i):
d = str((datetime.datetime.now() - datetime.timedelta(days=i)).date()).split("-")
timeoffile = d[0] + d[1] + d[2]
return(timeoffile)
# new file
def get_newfile(i):
filename = get_datetime(i)
aimPath = 'C:\\data\\' + filename
isExists=os.path.exists(aimPath)
if not isExists:
os.makedirs(aimPath)
print(aimPath + 'ok!')
return aimPath
else:
print(aimPath + 'file is exists!')
return False
def delete_flie(filePath):
for i,j,k in os.walk(filePath):
n = 0
while n < len(k):
fileneed = filePath + '\\' + k[n]
if(os.path.exists(fileneed)):
os.remove(fileneed)
else:
pass
n = n + 1
# get file name and move
def get_filename(filePath):
for i,j,k in os.walk(filePath):
n = 0
while n < len(k):
fileneed = filePath + '\\' + k[n]
if(os.path.exists(fileneed)):
shutil.move(fileneed,aimPath)
else:
pass
n = n + 1
# Monday special
def is_Monday():
if datetime.datetime.now().weekday() == 0:
return 3
else:
return 1
filePath = 'C:\\data'
pos = is_Monday()
aimPath = get_newfile(pos)
get_filename(filePath)
delete_flie(filePath)
该函数调用get_datetime函数,获得指定日期,并按照YYYYMMDD的格式将日期拼接;
使用isExists,来对文件名是否存在进行校验,如果改文件夹不存在,则新建文件夹。
在移动结束后,删除原目录的文件;
在删除前要使用os.path.exists验证待删除文件是否存在。
获取date文件夹内的文件名,并将其移动到新文件夹内;
在移动前要使用os.path.exists验证待移动文件是否存在。
周一的时候需要将周五、周六、周日的文件都放在以周五日期命名的文件夹中,所以使用这个函数来判断是星期几;
datetime.datetime.now().weekday()函数是0-6来表示周一-周五,所以值为0的时候,返回3;
这个函数的值将传给get_newfile,再调用get_datetime函数,通过控制这段的i,来控制生成的日期时间:
d = str((datetime.datetime.now() - datetime.timedelta(days=i)).date()).split("-")
注:shutil.copy会改变文件生成时间,不好对文件进行判断,所以要使用shutil.move移动文件
看完上述内容,你们对怎么在python中根据日期对文件进行归档有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。