Download a whole directory (containing files and subdirectories)
我想下载一个Linuxftp服务器上的特定目录,其中包含所有文件和子文件夹/子文件夹…
我发现这段代码只适用于Linux FTP服务器和Linux操作系统,但我的操作系统是Windows。我检查了代码,它只是复制了目录结构,所以用
以下是我当前的(非工作代码),我刚刚在相关地方用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | import sys import ftplib import os from ftplib import FTP ftp=FTP("ftpserver.com") ftp.login('user', 'pass') def downloadFiles(path,destination): #path & destination are str of the form"/dir/folder/something/" #path should be the abs path to the root FOLDER of the file tree to download try: ftp.cwd(path) #clone path to destination os.chdir(destination) print destination[0:len(destination)-1]+path.replace("/","\") os.mkdir(destination[0:len(destination)-1]+path.replace("/","\")) print destination[0:len(destination)-1]+path.replace("/","\")+" built" except OSError: #folder already exists at destination pass except ftplib.error_perm: #invalid entry (ensure input form:"/dir/folder/something/") print"error: could not change to"+path sys.exit("ending session") #list children: filelist=ftp.nlst() for file in filelist: try: #this will check if file is folder: ftp.cwd(path+file+"/") #if so, explore it: downloadFiles(path+file+"/",destination) except ftplib.error_perm: #not a folder with accessible content #download & return os.chdir(destination[0:len(destination)-1]+path.replace("/","\")) #possibly need a permission exception catch: ftp.retrbinary("RETR"+file, open(os.path.join(destination,file),"wb").write) print file +" downloaded" return downloadFiles("/x/test/download/this/",os.path.dirname(os.path.abspath(__file__))+"\") |
输出:
1 2 3 4 5 6 7 | Traceback (most recent call last): File"ftpdownload2.py", line 44, in <module> downloadFiles("/x/test/download/this/",os.path.dirname(os.path.abspath(__file__))+"\") File"ftpdownload2.py", line 38, in downloadFiles os.chdir(destination[0:len(destination)-1]+path.replace("/","\")) WindowsError: [Error 3] The system cannot find the path specified: 'C:\\ Users\\Me\\Desktop\\py_destination_folder\\x\\test\\download\\this\' |
有人能帮我完成这个代码吗?谢谢。
目录创建似乎类似于这个问题,除了由于Windows格式所做的更改之外,这个问题已经被问到了。
mkdir-p在python中的功能
如何在python中使用-p选项运行os.mkdir()?
因此,我建议输入mkdir_p函数,该函数显示在这些问题的已接受答案中,然后查看Windows是否会创建适当的路径
1 | os.mkdir(destination[0:len(destination)-1]+path.replace("/","\")) |
然后变成
1 2 | newpath = destination[0:len(destination)-1]+path.replace("/","\") mkdir_p(newpath) |
它使用os.makedirs(path)方法来获取完整路径。也可以用os.makedirs()替换os.mkdir()。
注意,如果在许多地方使用替换路径,那么只需继续使用newpath变量。在其他代码中,这可能更容易。