Python Collection 20150209
Recently, the case using python is getting more and more gradually. But, I have used python not high frequently so I forget a lot of things and whenever I look for the way how to write basic python code. It is not reasonable. So I begin collecting the basic sample code.
Before I have written about python examples in following articles. Those articles are included this series.
If-else
if x > 0: print "X is bigger than 0." else: print "X is less than 0."
If-elif-else
if x > 0: print "X is bigger than 0." elif x == 0: print "X is zero." else: print "X is less than 0."
File read and output(like cat which is major unix command line tool)
f = open('test-text.txt') data = f.read() f.close() lines = data.split('\n') for line in lines: if 0 < line.find(target) : print line
Send HTTP GET Requests
connection = httplib.HTTPSConnection(host) connection.request("GET", uri) response = json.loads(connection.getresponse().read()) print response
Send HTTP POST Requests
requestHeader = {"Content-type": "application/x-www-form-urlencoded"} connection = httplib.HTTPSConnection(host) connection.request("POST", uri, parameters, requestHeader) response = json.loads(connection.getresponse().read()) print response
If post data is json format, Content-type should be below.
requestHeader = {"Content-type":"application/json"}