How to implement a simple ftp client using python

Source: Internet
Author: User
Tags ftp client

How to implement a simple ftp client using python

This example describes how to implement a simple ftp client using python. Share it with you for your reference. The specific implementation method is as follows:

?

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

45

46

47

#! /Usr/bin/python

#-*-Coding: UTF-8 -*-

Import ftplib

Import OS

Import socket

HOST = 'ftp .w.illa.org'

DIRN = 'pub/mozilla.org/webtools'

FILE = 'bugzilla-3.6.9-to-3.6.10-nodocs.diff.gz'

Def writedata (data ):

F = open (FILE, 'wb ')

Try:

F. write (data)

Finally:

F. close ()

Def main ():

Try:

F = ftplib. FTP (HOST)

Handle T (socket. error, socket. gaierror ):

Print 'error: cannot reach "% s" '% HOST

Return

Print '*** Connected to host "% s"' % HOST

Try:

F. login ()

Failed t ftplib. error_perm:

Print 'error: cannot login anonymously'

F. quit ()

Return

Print *** Logged in as "anonymously "'

Try:

F. cwd (DIRN)

Failed t ftplib. error_perm:

Print 'errorl cannot CD to "% s" '% DIRN

F. quit ()

Return

Print *** Changed to "% s" folder '% DIRN

Try:

# Pass a callback function to retrbinary (), which is called every time a binary data is received

F. retrbinary ('retr % s' % FILE, writedata)

Failed t ftplib. error_perm:

Print 'error: cannot read file "% s" '% FILE

OS. unlink (FILE)

Else:

Print *** Downloaded "% s" to CWD '% FILE

F. quit ()

Return

If _ name _ = '_ main __':

Main ()

I hope this article will help you with Python programming.

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.