Posts Tagged ‘Code’

Python Code Snippet: Send a file to an FTP server

Monday, June 22nd, 2009

Here is a snippet of code I put together to take a file and upload it via FTP to a remote site.

import ftplib
# connect to the server
ftpsite = ftplib.FTP('ftpserver.address.com','FTPUSER','FTPPASSWD')
file = open('FileName.txt','rb')                # file to send
ftpsite.storbinary('STOR FileName.txt', file)   # send the file
file.close()                                    # close file and FTP
ftpsite.quit()

There are a crapload of similar code snippets available here: Seb Sauvage’s Python Snyppets. Thanks for putting all of these online, Seb!

Simple Example Usage of MySQLdb with Python

Thursday, June 18th, 2009

MySQLdb is a set of open source Python libraries that allow you to interact with MySQL databases at a higher level than the traditional C API methods.

Here is some code that takes two command line arguments, and stuffs them into a table as contents of the fields “ID” and “INPUT”.  (in other words it is a simple database of ID numbers and text).

#!/usr/bin/env python
#
# example of taking data from Python variables and inserting them into a database.
import MySQLdb, sys

id = sys.argv[1]
input = sys.argv[2] 

sql = "INSERT INTO your_table_name (id, input) VALUES("
sql += id
sql += ", '"
sql += input
sql += "')"

db = MySQLdb.connect(host="yourhost" db="yourdb", user="username", passwd="password" )
dbc = db.cursor()
dbc.execute(sql)

It’s JUST THAT EASY! :D