webgo/filehandling.py

85 lines
No EOL
1.8 KiB
Python

import os,tempfile,dircache,string,commands
def gen_temp_dir(prefix=None):
"""generate a secure temporary directory. returns name of dir."""
dirname=tempfile.mkdtemp("",prefix)
dirname+="/"
return dirname
def read_file(filename):
"""
read from the file whose name is given
@param filename String : name of file to read from
@return String: content of given file or None
"""
try:
f = open(filename,"r")
filecontent = f.read()
f.close()
except:
#TODO:if debug >=1:
print "(EE)[%s]: \"%s\" is not readable!"%(__name__, filename)
return ""
return filecontent
def is_dir_readable(path):
"""
Gets the name of a directory.
returns True if dir is readable, else False.
"""
return os.access(path,os.R_OK)
def write_file(filename,content):
"""
Write content to the given filename.
gets: filename,content.
"""
try:
f = open(filename,"w")#oeffnen und schliessen =>
f.close() #datei ist jetzt genullt
f = open(filename,"a") #anhaengend oeffnen
f.write(content)
f.close()
return ""
except:
#TODO: debug
#if self.debug >=1:
print "(EE)[%s]: \"%s\" is not writeable!"%(__name__, filename)
return filename
def basename(filename):
return os.path.basename(filename)
def make_all_dirs_absolute(prefix,dirlist):
"""
this function gets an absolute pathname and a list of pathnames
relative to the first. It returns this list, but with absolute
entries.
"""
ret=[]
for element in dirlist:
ret.append(os.path.normpath(prefix+"/"+element))
return ret
def gen_temp_dir(prefix='pk'):
'''returns the name of a secure temporary directory
with optional prefix as parameter'''
dirname=tempfile.mkdtemp("",prefix)
dirname+="/"
return dirname
def gen_temp_file(suffix="--gnugo"):
"""
returns the name of a generated temporay file.
optionally gets a suffix for the filename.
"""
return tempfile.mkstemp(suffix)[1]