Python's FTP module

Source: Internet
Author: User

Python itself with an FTP module, you can easily implement FTP upload, download and other operations. Here's how to use:

from ftplib import FTPimport socket    #用来设置超时时间FTP.connect(服务器地址,端口,超时时间)      # 连接服务器FTP.login(用户名,用户密码)        # 用户登录FTP.pwd(路径)                    # 读取操作路径FTP.cwd(路径)                    # 设置要操作FTP文件夹路径FTP.nlst()            # 获得目录下文件FTP.retrbinary(文件名, 回调函数)     # 下载FTP上的文件FTP.delete(文件名)                # 删除FTP文件FTP.storbinary(文件名, 文件对象 [,块大小])     # 上传FTP文件FTP.quit()                      # 退出FTP服务器FTP.set_pasv(boolean)           # 是否设置为被动模式FTP.rename(old, new)            # 重命名FTP.delete(path)                # 删除文件FTP.mkd(directory)              # 创建目录

An upload code:

import socketfrom ftplib import FTPftp_server=‘xx.xx.xx.xx‘ftp_user=‘xxxxx‘ftp_password=‘xxxxx‘ftp_backup_dir=‘backup‘newday = date.today()    #获取今天的日期oldday = date.today()-timedelta(5)    #获得5天前的日期newfile = ‘/home/backup/‘ + ‘backup_data_‘ + str(newday.year) + ‘.‘ + str(newday.month) + ‘.‘ +  str(newday.day) + ‘.zip‘    #本次备份文件名(绝对路径)oldfile = ‘/home/backup/‘ + ‘backup_data_‘ + str(oldday.year) + ‘.‘ + str(oldday.month) + ‘.‘ +  str(oldday.day) + ‘.zip‘    #5天前备份的文件名(绝对路径)def upload():    socket.setdefaulttimeout(60)    #超时FTP时间设置为60秒    ftp = FTP(ftp_server)    print("login ftp...")    try:        ftp.login(ftp_user, ftp_password)        print(ftp.getwelcome())   #获得欢迎信息        try:            if ftp_backup_dir in ftp.nlst():                print("found backup folder in ftp server, upload processing.")            else:                print("don‘t found backup folder in ftp server, try to build it.")                ftp.mkd(ftp_backup_dir)        except:            print("the folder" + ftp_backup_dir + "doesn‘t exits and can‘t be create!")            sys.exit()    except:        print("ftp login failed.exit.")        sys.exit()    ftp.cwd(ftp_backup_dir)    #设置FTP路径    print("upload data...")    try:        ftp.storbinary(‘STOR ‘ + os.path.basename(newfile), open(newfile,‘rb‘), 1024)    #上传备份文件    except:        print("upload failed. check your permission.")        print("delte old file...")    try:        ftp.delete(os.path.basename(oldfile))    #删除5天前的备份文件    except:        print("the old file in ftp doesn‘t exists, jumped.")    print("ftp upload successful.exit...")    ftp.quit()if __name__== ‘__main__‘:    upload()

Example 2:

Ftpserver = "192.168.0.1"

#EstablishFtpConnection
FTP = Ftplib. FTP (Ftpserver)
# FTPUser authentication
Ftp.login (' Administrator ',' Sunfast ')
#SwitchFtpOperating Directory
FTP.CWD ("/fromcovisint/094200005560743089chn03_830")
for filenameIn Ftp.nlst ():#GetFtpManipulate all files of the directory
If Os.path.splitext (filename) [1].upper () = =‘. CSV ':
If' Finished 'In filename:
Continue
Else
Try
#Download the specified file into the current operation directory
Ftp.retrbinary (' RETR%s '% filename,Open (filename,' WB '). Write)
#ftp. Storbinary (' STOR%s '% filename, open (filename, ' RB '), Const_buffer_size) FTPUploading files
#Import data
Self.import_data (Os.path.join (OS.GETCWD (), filename))
New_filename = os.path.splitext (filename) [0] + "_finished" + os.path.splitext (filename) [1]
# Modify the file name on the FTP directory , using the new file name
Ftp.rename (filename, new_filename)
finally:
# Delete the downloaded file details in the current directory
Os.remove (Os.path.join (OS.GETCWD (), filename)
Ftp.quit ()

Reference Documentation:

http://doublewei369.blog.163.com/blog/static/342947812012923113356945/

http://blog.csdn.net/wklken/article/details/7059423

http://wangwei007.blog.51cto.com/68019/983638

Python's FTP module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.