Set - 5

Question 6 :

How do I delete a file? (And other file questions...)

Answer :

Use os.remove(filename) or os.unlink(filename);


Question 7 :

How do I copy a file? 

Answer :

The shutil module contains a copyfile() function.

Question 8 :

How do I read (or write) binary data?

Answer :

or complex data formats, it's best to use the struct module. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa. 
For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:

import struct 
f = open(filename, "rb") # Open in binary mode for portability
s =
x, y, z = struct.unpack(">hhl", s)

The '>' in the format string forces big-endian data; the letter 'h' reads one "short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the string.

Question 9 :

How do I run a subprocess with pipes connected to both input and output?

Use the popen2 module. For example:

Answer :

import popen2
fromchild, tochild = popen2.popen2("command")
output = fromchild.readline()


Question 10 :

How can I mimic CGI form submission (METHOD=POST)? 
I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily? 

Answer :

Yes. Here's a simple example that uses httplib:

import httplib, sys, time 
### build the query string
qs = "First=Josephine&MI=Q&Last=Public"
### connect and send the server a path
httpobj = httplib.HTTP('www.some-server.out-there', 80)
httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
### now generate the rest of the HTTP headers...
httpobj.putheader('Accept', '*/*')
httpobj.putheader('Connection', 'Keep-Alive')
httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
httpobj.putheader('Content-length', '%d' % len(qs))
### find out what the server said in response...
reply, msg, hdrs = httpobj.getreply()
if reply != 200:

Note that in general for URL-encoded POST operations, query strings must be quoted by using urllib.quote(). For example to send name="Guy Steele, Jr.":

>>> from urllib import quote
>>> x = quote("Guy Steele, Jr.")
>>> x
>>> query_string = "name="+x
>>> query_string