Posts tagged ‘python programming linux ftp’

FTP made easy with Python

I am falling in love with python every day - its amazing how simple it makes tasks. The indented syntax and the functional aspects of the languages are growing on me every day.

Python comes with a bunch of libraries to make your life easy and one of them is ftplib. Here is a little script to list, chage directories and ultimately download a binary and a text file:

from ftplib import FTP
import getpass
serverName = "ahlawat.net"
ftp = FTP(serverName, raw_input("Username: "), getpass.getpass())
#change working directory
ftp.cwd("ftp")

#list the files
print ftp.dir()

baseDir = "c:/dev/python/pytest/pkg/"

#transfer a text file - some script
f = open(baseDir + "testUrl.groovy", "w")
ftp.retrlines("RETR testUrl.groovy", lambda x : f.write(x))
f.close()

#trasnfer a binary file - a png image
f = open(baseDir + "cube_logo.png", "wb")
ftp.retrbinary("RETR cube_logo.png", lambda x : f.write(x))
f.close()

More to come ..