【问题标题】:copy a list of files+directories with shutil with Python 3.XX使用 Python 3.XX 使用 shutil 复制文件+目录列表
【发布时间】:2021-09-08 08:48:53
【问题描述】:

我必须将文件+文件夹从本地目录复制到远程目录(LAN 网络)

为了提高效率,我只想复制远程目录中不存在的文件和目录。

为此,我尝试了这个:

获取缺失元素的列表:

lst_difference_cible = sorted(set.difference(set(localfiles), set(distfiles)))

然后将此列表的元素复制到临时文件夹(_SOURCE_TEMP)

for files in lst_difference_cible:
   shutil.copy2(files, _SOURCE_TEMP)

然后使用pysftp将temp文件夹的内容上传到远端

with pysftp.Connection(host=_RMTHOST, username=_USR, password=_DESTPASS) as sftp:
    sftp.put_r(_SOURCE_TEMP, _DEST)

它适用于文件,但不适用于目录。我尝试了 shutil.copytree 和许多其他解决方案,但我总是收到错误“路径预期,而不是列表”

这是我的脚本的一部分:

# création de liste récursive de fichiers locaux
localfiles = os.listdir(_SOURCE)

print("fichiers sur répertoire source: \n ")
for f in localfiles:
    print(f)

#connexion pour listing fichiers présents répertoire distant
ssh = paramiko.SSHClient()

# importation auto de clé de connexion avec le client
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
ssh.connect(_RMTHOST, username=_USR, password=_DESTPASS)

ftp = ssh.open_sftp()
distfiles = ftp.listdir(_DEST)
print("fichiers sur répertoire de destination: \n")
for f in distfiles:
    print(f)

ssh.close()
ftp.close()


# list of the files/folders not existing in dist folder
lst_difference_cible = sorted(set.difference(set(localfiles), set(distfiles)))


if lst_difference_cible:

    print("Dossiers/fichiers non présents dans le répertoire de destination " + _DEST )
    print(lst_difference_cible)

# création du répertoire temporaire pour copie
_SOURCE_TEMP = (_SOURCE + "temp")

if not os.path.exists(_SOURCE_TEMP):
    os.makedirs(_SOURCE_TEMP, exist_ok=True)

#copie des fichiers absents du répertoire distant sur le dossier temporaire pour transfert

os.chdir(_SOURCE)

#for directory in lst_difference_cible:
   #shutil.copytree(directory, _SOURCE_TEMP, ignore=ignore_fonction)

for files in lst_difference_cible:
   shutil.copy2(files, _SOURCE_TEMP)

#copie des fichiers dans le répertoire distant

with pysftp.Connection(host=_RMTHOST, username=_USR, password=_DESTPASS) as sftp:
    sftp.put_r(_SOURCE_TEMP, _DEST)

    sftp.close()

我不得不说我是一个非常早的初学者,我为我的脚本质量差表示歉意,但我真的尽力了,我尝试了很多天来解决我的问题,但我卡住了。

你能帮我吗?

【问题讨论】:

  • 抱歉,我对 FTP 几乎一无所知,我无法测试您的这部分代码。您是否设法以这种方式在服务器上创建文件夹?只是一个文件夹。只是要确定。因为这个任务的其余部分对我来说看起来相当微不足道。

标签: python list file directory copy


【解决方案1】:

我更准确地问了这个问题,@Yuri Khristich 帮了我很多,这是 SO 解决方案的链接: Compare two lists of filenames + size+ modification time

【讨论】:

    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 2010-11-19
    相关资源
    最近更新 更多