英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论