python - FileMover 24 小时 - Python

标签 python datetime shutil

所以我应该移动新的并且在 24 小时内编辑过的文件(.txt)。扩展名为 .txt 的文件应该从文件夹 A 移动到 B。我的代码可以工作,但是,每次我按 F5 运行程序时,它一次移动一个文件。有人可以帮我通过单击一次来移动所有文件吗?

谢谢

import os
import datetime
import shutil

source = ("/Users/SD/Desktop/A")
destination = ("/Users/SD/Desktop/B")
currentTime = datetime.datetime.now()
oldFile = currentTime - datetime.timedelta(hours=24)
for files in os.listdir(source):
    if files.endswith('.txt'):
        path = os.path.join(source, files)
        st = os.stat(path)
        mTime = datetime.datetime.fromtimestamp(st.st_mTime)

        if mTime > oldFile:
            print('{} ~ last modified {}'.format(path, mTime))

fileSource = os.path.join(source, files)
fileDestination = os.path.join(destination, files)
shutil.move(fileSource, fileDestination)
print("\tMoved {} to {}.\n".format(files, destination))

最佳答案

我认为在您的代码中,您的缩进已关闭,您将文件移动到 for 循环之后。这会导致仅移动 for 循环的最后一个文件。将最后一段代码移动到循环内,特别是最后一个 if 语句内,以移动与您的条件匹配的任何文件。

此外,您的时间测试确实让我感到困惑,我怀疑它是否达到了您的预期。我已经用(对我来说)更清晰的测试取代了它......

import os
import datetime
import shutil

source = ("/Users/../Desktop/A")
destination = ("/Users/../Desktop/B")
currentTime = datetime.datetime.now()
for files in os.listdir(source):
    if files.endswith('.txt'):
        path = os.path.join(source, files)
        st = os.stat(path)
        #---New Time Test setup---#
        tDelta = currentTime - datetime.datetime.fromtimestamp(st.st_mtime)
        maxDelta = 24*3600
        if tDelta.total_seconds() < maxDelta:
            print('{} ~ last modified {}'.format(path, tDelta))
            fileSource = os.path.join(source, files)
            fileDestination = os.path.join(destination, files)
            shutil.move(fileSource, fileDestination)
            print("\tMoved {} to {}.\n".format(files, destination))

之前的文件:

..\Desktop\A\
  -text_a.txt
  -text_b.txt
..\Desktop\B\
  ~Empty~

之后的文件:

..\Desktop\A\
  ~Empty~
..\Desktop\B\
  -text_a.txt
  -text_b.txt

PS:我认为您的代码中有一个小错误,oldFile 应该是 dayOld ,反之亦然。您应该编辑此...

关于python - FileMover 24 小时 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44920061/

相关文章:

python - Class_weight 和 sample_weight 对 sklearn Random Forest 无效

Javascript - 从 rawOffset Google 时区 API 计算时间

python - OSError : [Error 1] Operation not permitted shutil. 移动

python - 结合 pandas 和 shutil 时与解码相关的错误

python - 如何使用getattr调用字符串作为属性?

python - 在 EMR 上运行 pyspark 脚本

javascript - JS : how to get current datetime?

Python删除所有文件夹但不删除文件

python - 有没有办法连接子列表中的字符串列表

python - 推断日期格式与传递解析器