1 #FTP Operation2 ImportFtplib3 4Host ='192.168.20.191'5Username ='Ftpuser'6Password ='ftp123'7File ='1.txt'8 9f = ftplib. FTP (host)#instantiating an FTP objectTenF.login (username, password)#Login One A #Get current path -Pwd_path =f.pwd () - Print("ftp current path:", Pwd_path) the - - #read the FTP text file line by row - #f.retrlines (' RETR%s '% file) + - defftp_download (): + " "download files in binary format" " AFile_remote ='1.txt' atFile_local ='D:\\test_data\\ftp_download.txt' -BufSize = 1024#Set Buffer size -fp = open (file_local,'WB') -F.retrbinary ('RETR%s'%file_remote, Fp.write, bufsize) - fp.close () - in - defftp_upload (): to " "uploading files in binary form" " +File_remote ='Ftp_upload.txt' -File_local ='D:\\test_data\\ftp_upload.txt' theBufSize = 1024#Set Buffer size *fp = open (file_local,'RB') $F.storbinary ('STOR'+file_remote, FP, bufsize)Panax Notoginseng fp.close () - the + ftp_download () A ftp_upload () the f.quit () +
FTP Object Method Description
- Login (user= ' anonymous ', passwd= ', acct= ') log in to the FTP server, all parameters are optional
- PWD () Gets the current working directory
- CWD (path) sets the current working directory to the path shown in
- Dir ([path[,... [, CB]]) Displays the contents of the path directory, the optional parameter CB is a callback function that is passed to the Retrlines () method
- Nlst ([path[,...]) is similar to Dir (), but returns a list of file names instead of displaying them
- Retrlines (cmd [, CB]) given an FTP command (such as "RETR filename") for downloading a text file. Optional callback function CB is used to process each line of the file
- Retrbinary (cmd,cb[,bs=8192[, RA]) is similar to Retrlines (), except that this instruction handles binary files. callback function CB is used to process each piece (block size default is 8KB) downloaded data
- Storlines (cmd, f) is given an FTP command (such as "STOR filename"), which is used to upload a text file. To be given a file object F
- Storbinary (cmd, f,[,bs=8192]) is similar to Storlines (), except that this instruction handles binary files. To give a file object F, upload block size BS defaults to 8KB
- Rename (old, new) rename the remote file old to new
- Delete (path) deletes the remote file located in path
- MKD (directory) to create a remote directory
- RMD (directory) Delete remote directory
- Quit () Close the connection and exit
Python ftp upload and download