python shutil 根据条件从源目录复制文件到远程目录

python shutil copy the files from source dir to remote dir based on condition

我希望使用 shutil() 将文件从源目录复制到远程目录,但是我需要进行如下检查。

  1. 不要将零字节文件复制到远程。

  2. 如果文件已经存在于远程,则不要再次复制它,除非源中的文件已更改内容或更新。

  3. 我正在寻找当月的目录,因此,如果当月可用,则遍历到该目录,例如当月应该是一月。

正在导入模块:

import os
import glob
import shutil
import datetime

选择当前月份的变量:

Info_month = datetime.datetime.now().strftime("%B")

代码片段:

for filename in glob.glob("/data/Info_month/*/*.txt"):
    if not os.path.exists("/remote/data/" + os.path.basename(filename)):
        shutil.copy(filename, "/remote/data/")

上面的代码没有使用变量 Info_month 但是,硬编码目录名是可行的。

由于缺乏 Python 知识,我遇到了挑战。

如何将变量 Info_month 包含到源目录路径中?

如何勾选不复制零字节文件?

os.path.getsize(fullpathhere) > 0

我的基本愚蠢逻辑:

for filename in glob.glob("/data/Info_month/*/*.txt"):
    if os.path.getsize(fullpathhere) > 0 :
        if not os.path.exists("/remote/data/" + os.path.basename(filename)):
            shutil.copy(filename, "/remote/data/")
    else:
        pass

这是对现有脚本的修复。这还没有尝试实现 "source newer than target" 逻辑,因为您没有具体询问这个问题,而且可以说这已经太宽泛了。

for filename in glob.glob("/data/{0}/*/*.txt".format(Info_month)):
    # The result of the above glob _is_ a full path
    if os.path.getsize(filename) > 0:
        # Minor tweak: use os.path.join for portability
        if not os.path.exists(os.path.join(["/remote/data/", os.path.basename(filename)])):
            shutil.copy(filename, "/remote/data/")
    # no need for an explicit "else" if it's a no-op