在Python 3.X中,是否可能使用FTP传输文件夹?

huangapple go评论76阅读模式
英文:

Is it possible to transfer a folder using FTP in Python 3.X?

问题

我想知道是否可以使用FTP服务器传输文件夹。这将使一次传输多个文件变得更加容易。但请注意,文件夹内可能包含其他文件夹,这些文件夹内又包含它们自己的文件。如果这是可能的,请告诉我如何实现。如果不可能,是否有其他方法可以代替FTP?

谢谢!

英文:

As you know from the title I am wondering if it is possible to transfer a folder using an FTP server. This would make it a lot easier to transfer multiple files all at once. Keep in mind however that the folder will likely contain other folders inside of it that all contain their own files. If this is possible please leave a response as to how I could achieve this. If it is not possible, is there any other method I could use rather than FTP?

Thanks!

答案1

得分: 0

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" 上传文件 {name} ...", end="")
with open(local_path, 'rb') as file:
ftp.storbinary(f'STOR {name}', file)
print(" 完成。")
elif os.path.isdir(local_path):
print(f"创建目录 {name} ...", end="")
try:
ftp.mkd(name)
except:
print(" 已存在。", end="")
print(" 进入目录 ...", end="")
ftp.cwd(name)
print(" 完成。")
upload_dir(ftp, local_path)
print(f" 返回上级目录 ...", end="")
ftp.cwd('..')
print(" 完成。")

ftp = FTP('ftp.whatever.com') # 或您的FTP服务器
ftp.login('用户名', '密码') # 使用您的用户名和密码登录

upload_dir(ftp, '本地目录路径') # 您的本地目录路径

ftp.quit()

英文:
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()

huangapple
  • 本文由 发表于 2023年6月29日 05:33:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576845.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定