source: ndgCommon/trunk/ndg/common/src/lib/fileutilities.py @ 7761

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/ndgCommon/trunk/ndg/common/src/lib/fileutilities.py
Revision 7761, 4.1 KB checked in by sdonegan, 9 years ago (diff)

includes extra method for copying files

Line 
1'''
2Various helper methods for setting up and cleaning filesystems
3C Byrom Apr 08
4'''
5import os, sys, logging
6from os import makedirs
7from os.path import normpath,dirname,exists,abspath
8
9   
10def createFile(fileName, content):
11    '''
12    Create a file with the specified name and content
13    @param fileName: name of file to create
14    @param content: content of file to create 
15    '''
16    try:
17        f = open(fileName,'w')
18        f.write(content)
19        f.close()
20    except:
21        raise SystemError, "ERROR: Problem encountered when creating file, %s" %fileName
22
23
24def makepath(path):
25    ''' creates missing directories for the given path and
26        returns a normalized absolute version of the path.
27
28    - if the given path already exists in the filesystem
29      the filesystem is not modified.
30
31    - otherwise makepath creates directories along the given path
32      using the dirname() of the path. You may append
33      a '/' to the path if you want it to be a directory path.
34
35    from holger@trillke.net 2002/03/18
36    @return normalised file path
37    '''
38    logging.info("Creating dir: " + path) 
39    dpath = normpath(dirname(path))
40    if not exists(dpath):
41        makedirs(dpath)
42    npath = normpath(abspath(path))
43   
44    logging.info("Directory created successfully")
45    return npath
46
47
48def createDir(dir):
49    '''
50    Create a new dir, if required
51    @param dir: directory to create
52    @raise IOError: if problems occur whilst creating directory
53    '''
54    logging.info("Creating directory, %s" %dir)
55    status = 0
56    if not os.path.exists(dir):
57        if not dir.endswith(os.sep):
58            dir += os.sep
59        makepath(dir)
60    else:
61        logging.info("- directory already exists")
62   
63
64
65def setUpDir(dir):
66    '''
67    Clean out specified directory - or create this, if it doesn't already exist
68    @param dir: directory to set up/clean
69    '''
70    logging.info("Setting up directory, " + dir)
71    if os.path.isdir(dir):
72        cleanDir(dir)
73    else:
74        try:
75            makepath(dir)
76        except:
77            sys.exit("Failed at setting up directory, %s" %dir)
78
79    logging.info("Directory set up successfully")
80
81
82def cleanDir(dir):
83    '''
84    Remove all files from the specified directory
85    @param dir: directory to clean
86    '''
87    logging.info("Cleaning dir " + dir)
88    # add in a little safety check here - we don't want to delete large chunks
89    # of the filesystem by accident...
90    if dir.strip().startswith('/') and len(dir) < 5:
91        raise ValueError("Top level directory specified (or something close to this) - will not delete the entire system")
92
93    for root, dirs, files in os.walk(dir, topdown=False):
94        for name in files:
95            os.remove(os.path.join(root, name))
96        for name in dirs:
97            os.rmdir(os.path.join(root, name))
98    logging.info("Directory cleaned successfully")
99
100   
101def makeBackUp(original_dir, backup_dir):
102    '''
103    Copy contents of original dir into backup dir
104    @param original_dir: dir to backup
105    @param backup_dir: dir to backup to 
106    '''
107    logging.info("Creating backup directory (" + original_dir + \
108                            " --> " + backup_dir + ")")
109    makepath(backup_dir)
110
111    commandline = "find " + original_dir + " -type f -print | xargs -i cp \{\} " + backup_dir
112    logging.info("Executing : " + commandline)
113    status = os.system(commandline)
114    if status !=0:
115        sys.exit("Failed at copying to backup directory %s" %backup_dir)
116       
117    logging.info("Backup completed successfully")
118   
119
120def copyFileToDir(original_file, destination_dir):
121    '''
122    Copy contents of file to  new dir
123    @param original_file: file to copy
124    @param destination_dir: dir to copy it to 
125    '''
126    logging.info("Copying file (" + original_file + \
127                            " --> " + destination_dir + ")")
128    makepath(destination_dir)
129
130    commandline = "cp " + original_file + " " + destination_dir
131    logging.info("Executing : " + commandline)
132    status = os.system(commandline)
133    if status !=0:
134        sys.exit("Failed at copying to new directory %s" %destination_dir)
135       
136    logging.info("Copy completed successfully")
137
138   
139
Note: See TracBrowser for help on using the repository browser.