我必须使用 Python 脚本自动将文件夹上传到 FTP。我可以上传单个文件,但不能上传包含子文件夹和文件的文件夹。我做了很多搜索,但没有成功。有人可以帮我吗?提前致谢。
#! /usr/bin/python
import ftplib
s = ftplib.FTP('serverip','usrname','password')
file = '/home/rock/test.txt'
ftppath = '/IT'
filename = "rak"
s.cwd(ftppath)
f = open(file,'rb')
s.storbinary('STOR ' + filename, f)
f.close()
s.quit()
最佳答案
我最近遇到了这个问题,想出了一个递归函数来解决它。
import ftplib
import os
server = 'localhost'
username = 'generic_user'
password = 'password'
myFTP = ftplib.FTP(server, username, password)
myPath = r'c:\temp'
def uploadThis(path):
files = os.listdir(path)
os.chdir(path)
for f in files:
if os.path.isfile(path + r'\{}'.format(f)):
fh = open(f, 'rb')
myFTP.storbinary('STOR %s' % f, fh)
fh.close()
elif os.path.isdir(path + r'\{}'.format(f)):
myFTP.mkd(f)
myFTP.cwd(f)
uploadThis(path + r'\{}'.format(f))
myFTP.cwd('..')
os.chdir('..')
uploadThis(myPath) # now call the recursive function
关于python - 使用 Python 脚本将文件夹从本地系统上传到 FTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5663787/