windows 在Python 3.X中可以使用FTP传输文件夹吗?[副本]

6rqinv9w  于 2023-06-30  发布在  Windows
关注(0)|答案(1)|浏览(98)

此问题已在此处有答案

How do I upload full directory on FTP in python? [duplicate](1个答案)
Upload folders from local system to FTP using Python script(7个回答)
昨天关门了。
正如你从标题中所知道的,我想知道是否有可能使用FTP服务器传输文件夹。这将使一次传输多个文件更加容易。但是请记住,该文件夹可能包含其他文件夹,这些文件夹都包含自己的文件。如果这是可能的,请留下一个答复,我如何才能实现这一点。如果不可能,除了FTP,还有其他方法可以使用吗?
谢谢!

64jmpszr

64jmpszr1#

import os
from ftplib import FTP

def upload_dir(ftp, path):
    for name in os.listdir(path):
        local_path = os.path.join(path, name)
        if os.path.isfile(local_path):
            print(f"  uploading file {name} ...", end="")
            with open(local_path, 'rb') as file:
                ftp.storbinary(f'STOR {name}', file)
            print(" done.")
        elif os.path.isdir(local_path):
            print(f"making directory {name} ...", end="")
            try:
                ftp.mkd(name)
            except:
                print(" already exists.", end="")
            print(" navigating into ...", end="")
            ftp.cwd(name)
            print(" done.")
            upload_dir(ftp, local_path)
            print(f" navigating up ...", end="")
            ftp.cwd('..')
            print(" done.")

ftp = FTP('ftp.whatever.com')  # or your FTP server
ftp.login('USER', 'PW')  # login with your username and password

upload_dir(ftp, 'path/to/your/directory')  # your local directory path

ftp.quit()

相关问题