简体   繁体   English

Python:将文件从一个文件夹复制到2天前创建的另一个文件夹

[英]Python: Copy files from a folder to another that created 2 days ago

I want to copy the files that have been created two days ago from a folder to an other. 我想将两天前创建的文件从一个文件夹复制到另一个文件夹。

This is my code: 这是我的代码:

src = '/home/user'
dst = '/var/tmp/backup_tmp'

two_days = datetime.now() - timedelta(days=2)
filetime = datetime.fromtimestamp(path.getctime(src))

for file in os.listdir(src):
  if file not in os.listdir(dst) and os.path.isfile(file):
    if filetime <= two_days:
       print "File is more than two days old"
    else:
       shutil.copy(os.path.join(src, file), dst)

I do not have any errors when I run the script but the files not copy to my destination folder. 运行脚本时我没有任何错误,但是文件没有复制到我的目标文件夹中。

Can you help me to find where is the wrong with this??? 您能帮我找出问题出在哪里吗???

BRs, Spyros BR,Spyros

You calculating filetime outside if the loop. 您在循环之外计算文件时间。 Seems like this is a your problem. 似乎这是您的问题。 Try: 尝试:

for f in os.listdir(src):
  filetime = datetime.fromtimestamp(path.getctime(os.path.join(src,f)))
  if f not in os.listdir(dst) and os.path.isfile(f):
    if filetime <= two_days:
       print "File is more than two days old"
    else:
       shutil.copy(os.path.join(src, f), dst)

The problem was the statement: "if f not in os.listdir(dst) and os.path.isfile(f):" When I removed it everything works properly. 问题是这样的说法:“如果f不在os.listdir(dst)和os.path.isfile(f)中:”当我删除它时,一切正常。

BRs, Spyros BR,Spyros

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM