How to specify the local destination folder when extracting files from FTP

The current code will load the deleted XML files in the directory where this program is located. How to specify a different local directory as the destination?

Please also tell me if there is any weird code here. :)

import ftplib import os import os import socket HOST = 'ftp.server.com' DIRN = 'DirectoryInFTPServer' filematch = '*.xml' username = 'username' password = 'password' def main(): try: f = ftplib.FTP(HOST) except (socket.error, socket.gaierror), e: print 'ERROR: cannot reach "%s"' % HOST return print '*** Connected to host "%s"' % HOST try: f.login(username, password) except ftplib.error_perm, e: print 'ERROR: cannot login' f.quit return print '*** Logged in successfully' try: f.cwd(DIRN) except ftplib.error_perm, e: print 'ERROR: cannot CD to "%s"' % DIRN f.quit() print '*** Changed to folder: "%s"' % DIRN try: s = 0; for filename in f.nlst(filematch): fhandle = open(filename, 'wb') print 'Getting ' + filename f.retrbinary('RETR ' + filename, fhandle.write) s = s + 1 except ftplib.error_perm, e: print 'ERROR: cannot read file "%s"' % filename os.unlink(filename) f.quit() print 'Files downloaded: ' + str(s) return if __name__ == '__main__': main() 
+4
source share
2 answers

Use os.chdir () to change the local working directory and then change it after extracting the files.

I added the added lines using ####

 import ftplib import os import os import socket HOST = 'ftp.server.com' DIRN = 'DirectoryInFTPServer' filematch = '*.xml' username = 'username' password = 'password' storetodir='DirectoryToStoreFilesIn' #### def main(): try: f = ftplib.FTP(HOST) except (socket.error, socket.gaierror), e: print 'ERROR: cannot reach "%s"' % HOST return print '*** Connected to host "%s"' % HOST try: f.login(username, password) except ftplib.error_perm, e: print 'ERROR: cannot login' f.quit return print '*** Logged in successfully' try: f.cwd(DIRN) except ftplib.error_perm, e: print 'ERROR: cannot CD to "%s"' % DIRN f.quit() print '*** Changed to folder: "%s"' % DIRN currdir=os.getcwd() #### try: os.chdir(storetodir)#### s = 0; for filename in f.nlst(filematch): fhandle = open(filename, 'wb') print 'Getting ' + filename f.retrbinary('RETR ' + filename, fhandle.write) s = s + 1 except ftplib.error_perm, e: print 'ERROR: cannot read file "%s"' % filename os.unlink(filename) os.chdir(currdir) #### f.quit() print 'Files downloaded: ' + str(s) return if __name__ == '__main__': main() 
+4
source

The default behavior of ftplib is to copy all files from the server to the current working directory (CWD).

To indicate where the files go, you can temporarily change the CWD using os.chdir() , and you can find the current CWD using os.getcwd()


Usage example:

 >>> import os >>> os.getcwd() 'C:\\python' >>> tmp_a = os.getcwd() >>> os.chdir('C:/temp') >>> os.getcwd() 'C:\\temp' >>> os.chdir(tmp_a) >>> os.getcwd() 'C:\\python' 
+3
source

All Articles