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 from __future__ import with_statement
28
29 __authors__ = [ "Marie-Francoise Incardona", "Olof Svensson", "Jérôme Kieffer" ]
30 __contact__ = "svensson@esrf.fr"
31 __license__ = "LGPLv3+"
32 __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
33 __date__ = "20120216"
34 __doc__ = """
35 This is a static utility class for handling of files.
36 """
37
38
39 import os, shutil
40 from EDVerbose import EDVerbose
44
45
46 @staticmethod
48 """
49 Reads and returns the content of a file.
50 @param _strFileName: Path to the file
51 @return: String containing the contents of the file.
52 """
53 strContent = None
54 try:
55 strContent = open(_strFileName, "rb").read()
56 except Exception, e:
57 strError = "EDUtilsFile.readFile: Reading %s: %s" % (_strFileName, str(e))
58 EDVerbose.ERROR(strError)
59 raise IOError(strError)
60 return strContent
61
62
63 @staticmethod
65 """
66 Writes a string to a file. If the string is not already in unicode
67 format it will be converted to unicode.
68 @param _strFileName: Path to file, will be created if not existing
69 @param _strContent: String content to be written to the file
70 """
71 try:
72 with open(_strFileName, "wb") as myFile:
73 if type(_strContent) == unicode:
74 myFile.write(_strContent)
75 else:
76 myFile.write(unicode(_strContent, errors='ignore'))
77 myFile.flush()
78 except Exception, e:
79 strError = "EDUtilsFile.writeFile: Writing %s: %s" % (_strFileName, str(e))
80 EDVerbose.ERROR(strError)
81 raise IOError(strError)
82
83
84 @classmethod
86 """
87 Returns the content of this file as a string.
88 Any environment variables present in the file are substituted, as well as
89 any occurrences of strings in the optional dictionary.
90 @param _strFileName: Path to the file
91 @param _dict: Optional dictoionary
92 """
93 strContent = cls.readFile(_strFileName)
94
95 strContent = os.path.expandvars(strContent)
96 if (_dict is not None):
97 for key in _dict.keys():
98 try:
99 strContent = strContent.replace(key , _dict[ key ])
100 except Exception:
101 EDVerbose.ERROR("%s: %s" % (key , _dict[ key ]))
102 return strContent
103
104 @staticmethod
106 """
107 Returns the file extension, e.g. "img" for "testscale_1_001.img"
108 @param _strFileName: String containing the file name
109 """
110 strFileExtension = None
111 strFileSplit = os.path.splitext(_strFileName)
112 if (len(strFileSplit) > 1):
113 strExtensionWithSeparator = strFileSplit[1]
114 if (len(strExtensionWithSeparator) > 1):
115
116 strFileExtension = strExtensionWithSeparator[1:]
117 return strFileExtension
118
119 @staticmethod
121 return os.path.basename(_strFileName)
122
123 @staticmethod
124 - def copyFile(_strSource, _strDestination):
125 shutil.copyfile(_strSource, _strDestination)
126
127 @staticmethod
129 if (_strFileName is not None):
130 if (os.path.exists(_strFileName)):
131 os.remove(_strFileName)
132