This recipe is a memory-based directory copier and paster. Pickled Directory objects will contain all data from a directory at path and can be saved in other locations. Once a Directory object has been created, pasting it to another location is extremely simple.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | '''Support module for working with directories.
This module provides several functions for
copying and pasting directories and files.'''
__version__ = 1.3
################################################################################
import os
class File:
'File(path) -> new file'
def __init__(self, path):
'Initializes a new file object.'
self.__name = os.path.basename(path)
self.__data = file(path, 'rb', 0).read()
def paste(self, path):
'Creates a new file at path.'
file(os.path.join(path, self.__name), 'wb', 0).write(self.__data)
class Directory:
'Directory(path) -> new directory'
def __init__(self, path):
'Initializes a new directory object.'
self.__name = os.path.basename(path)
self.__data = list()
for name in os.listdir(path):
path_name = os.path.join(path, name)
if os.path.isdir(path_name):
self.__data.append(Directory(path_name))
elif os.path.isfile(path_name):
self.__data.append(File(path_name))
def paste(self, path):
'Creates a new directory at path.'
if self.__name:
path = os.path.join(path, self.__name)
os.mkdir(path)
for item in self.__data:
item.paste(path)
################################################################################
if __name__ == '__main__':
import sys
print 'Content-Type: text/plain'
print
print file(sys.argv[0]).read()
|
This recipe is effective for pasting small directories to several different locations. Large directories can be copied, but performance drops when all of RAM is occupied. This recipe was mainly an experiment for grabbing a directory, storing it in memory, and then writting it back out to disk.