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 = f.read(8)
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")
tochild.write("input\n")
tochild.flush()
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:

#!/usr/local/bin/python 
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))
httpobj.endheaders()
httpobj.send(qs)
### find out what the server said in response...
reply, msg, hdrs = httpobj.getreply()
if reply != 200:
sys.stdout.write(httpobj.getfile().read())

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
'Guy%20Steele,%20Jr.'
>>> query_string = "name="+x
>>> query_string
'name=Guy%20Steele,%20Jr.'