我必须使用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()
我最近遇到了这个问题,并找到了一个递归函数来解决它。
您基本上需要使用os.walk()来获取这些文件并传输它们。
这是我为自己写的一个剧本,可以满足你的要求。 我很久以前写的,所以如果我再写一次,我可能会做得不同,但我从中得到很多用处。
它导入psftplib,这是我为putty sftp编写的包装器。 请随意删除这些引用,或在以下位置获取库: http://code.google.com/p/psftplib/source/browse/trunk/psftplib.py
编辑2017年12月20日:
为此,我在GitHub中编写了一个项目。Click for details!
上面有很好的答案,但是我还想使用ftputil包添加一个好的答案。如果需要将文件从本地目录上载到ftp目录,可以使用此递归函数:
如果决定使用此函数,则必须使用ftputil包连接ftp。为此,可以使用以下代码段:
所以,我们快结束了。最后一件事是对像我这样的初学者使用这个函数:
最重要的是路径末尾的“/”字符。你得把它放在最后。最后,我想分享整个代码:
相关问题 更多 >
编程相关推荐