# -*- coding: utf-8 -*-
"""erecord_cmn.utils.dir_and_file
Methods on directories and files
"""
import os
import shutil
import zipfile
import csv
import uuid
import xlwt
import xlrd
[docs]def is_a_directory(path):
""" Return True if path exists as a directory and else return False """
if os.path.exists(path):
if os.path.isdir(path):
return True
return False
[docs]def create_dir_if_absent(dirpath):
""" Create the directory dirpath if dirpath does not yet exist.
Returns True if the creation has been done.
"""
creation_done = False
if not os.path.exists(dirpath):
try:
os.mkdir(dirpath)
creation_done = True
except Exception as e :
msg = "unable to create directory "+dirpath
raise Exception(msg)
return creation_done
[docs]def create_dirs_if_absent(path_list):
for dirpath in path_list:
create_dir_if_absent(dirpath)
[docs]def delete_path_if_present(path):
""" Delete the path if it exists.
Returns True if the deletion has been done.
"""
deletion_done = False
if os.path.exists(path):
try:
if os.path.isfile(path):
os.remove(path)
deletion_done = True
elif os.path.isdir(path):
shutil.rmtree(path)
deletion_done = True
except Exception as e :
msg = "unable to delete "+dirpath
raise Exception(msg)
return deletion_done
[docs]def clean_dir(dirpath):
""" Create the directory dirpath after having deleting dirpath if still
existing.
"""
deletion_done = delete_path_if_present(dirpath)
creation_done = create_dir_if_absent(dirpath)
return (deletion_done, creation_done)
[docs]def make_csv_file(row_list, filename, dirpath, delimiter=";"):
"""Builds a csv file from row_list and saves it as filename under dirpath
"""
csvfile = os.path.join(dirpath, filename)
file = open(csvfile, "wb")
c = csv.writer(file, delimiter=delimiter)
for row in row_list:
c.writerow(row)
file.close()
[docs]def make_zip_folder(folderpath):
"""Builds the zip file of the folderpath.
Returns the zip file path name.
"""
format = 'zip'
shutil.make_archive( folderpath, format, folderpath)
zip_path = folderpath+'.'+format
return zip_path
[docs]def unzip_file(zip_file_path, path):
"""unzip zip_file_path into path.
Returns True if success, and else False.
"""
cr_ok = False
try :
zip_file = zipfile.ZipFile(file=zip_file_path)
zip_file.extractall(path=path)
cr_ok = True
except :
raise
return cr_ok
[docs]def save_posted_file(data, key, filepath) :
"""Save into the filepath file a file that is sent in POST data as key."""
cr_ok = False
if key in data.keys() :
try :
datafile = data[key]
with open(filepath, 'wb') as f:
for chunk in datafile.chunks():
f.write(chunk)
f.close()
cr_ok = True
except:
pass
return cr_ok
[docs]def get_available_pathname(rootpath, rootname):
"""Defines and returns a path name that doesn't yet exist.
The path name is based on rootname, is the one of a rootpath
subdirectory.
The pathname directory should be immediately created !
"""
found = False
while not found:
pseudoid = str(uuid.uuid4())
name = rootname + pseudoid
pathname = os.path.join(rootpath, name)
if not os.path.exists(pathname):
found = True
return pathname
[docs]def recursive_overwrite(src, dest):
"""recursive overwrite taking into account directories and files
Links are not taken into account
"""
try :
if os.path.isdir(src):
if not os.path.isdir(dest):
os.makedirs(dest)
files = os.listdir(src)
for f in files:
recursive_overwrite(os.path.join(src, f),
os.path.join(dest, f))
else:
shutil.copyfile(src, dest)
except :
raise
[docs]class WritableWorksheet(object):
"""further for a xlwt.Worksheet"""
COLUMN_LIMIT = 256
ROW_LIMIT = 65536
default_style = xlwt.XFStyle()
head_style = xlwt.XFStyle()
head_font = xlwt.Font()
head_font.bold = True
head_style.font = head_font
help_style = xlwt.XFStyle()
help_font = xlwt.Font()
help_font.italic = True
help_font.colour_index = 0x30 # blue 0x0C, brown 0x3c, light_blue 0x30
help_style.font = help_font
#help_pattern = xlwt.Pattern()
#help_pattern.pattern = xlwt.Pattern.SOLID_PATTERN
#help_pattern.pattern_fore_colour = xlwt.Style.colour_map['gray25']
#help_style.pattern = help_pattern
[docs] @classmethod
def write(cls, ws, row, col, v, style=None) :
"""Writes v into the (row, col) cell of the ws xlwt.Worksheet
Truncation : writes v if limits OK and else does nothing.
"""
if style is None :
style = cls.default_style
if (col < cls.COLUMN_LIMIT) and (row < cls.ROW_LIMIT) :
ws.write(row, col, v, style=style)
[docs] @classmethod
def write_title(cls, ws, row_ini, title):
"""Writes a title into a xlwt.Worksheet """
cls.write(ws, row_ini, 0, title, style=cls.head_style)
return row_ini
[docs] @classmethod
def write_help(cls, ws, row_ini, text):
"""Writes a help text into a xlwt.Worksheet """
cls.write(ws, row_ini, 0, text, style=cls.help_style)
return row_ini
[docs] @classmethod
def write_line_feed(cls, ws, row_ini):
"""Writes a line feed into a xlwt.Worksheet """
cls.write(ws, row_ini, 0, "")
return row_ini
[docs] @classmethod
def write_lines_byrow(cls, ws, row_ini, lines, nb_head=0, col_main=[]):
"""Writes lines into a xlwt.Worksheet (a row by line) """
last_row = row_ini
for rabs,row in enumerate(lines):
r = rabs + row_ini
for c,col in enumerate(row) :
if rabs < nb_head or c in col_main :
style=cls.head_style
else :
style=cls.default_style
cls.write(ws, r, c, col, style=style)
last_row = r
return last_row
[docs] @classmethod
def write_lines_bycol(cls, ws, row_ini, lines, nb_head=0, row_main=[]):
"""Writes lines into a xlwt.Worksheet (a col by line) """
last_row = row_ini
for r,row in enumerate(lines):
for cabs,col in enumerate(row) :
if cabs < nb_head or cabs in row_main :
style=cls.head_style
else :
style=cls.default_style
c = cabs + row_ini
cls.write(ws, c, r, col, style=style)
last_row = c
return last_row
[docs] @classmethod
def write_group_byrow(cls, ws, info_list, nb_head=0, col_main=[], row_ini=0,
title=None):
"""Writes title and info_list into a xlwt.Worksheet (a row by data)"""
if title is not None :
last_row = cls.write_title(ws=ws, row_ini=row_ini, title=title)
last_row = cls.write_line_feed(ws=ws, row_ini=last_row+1)
row_ini = last_row + 1
last_row = cls.write_lines_byrow(ws=ws, row_ini=row_ini,
lines=info_list, nb_head=nb_head, col_main=col_main)
return last_row
[docs] @classmethod
def write_group_bycol(cls, ws, info_list, nb_head=0, row_main=[], row_ini=0,
title=None):
"""Writes title and info_list into a xlwt.Worksheet (a col by data)"""
if title is not None :
last_row = cls.write_title(ws=ws, row_ini=row_ini, title=title)
last_row = cls.write_line_feed(ws=ws, row_ini=last_row+1)
row_ini = last_row + 1
last_row = cls.write_lines_bycol(ws=ws, row_ini=row_ini,
lines=info_list, nb_head=nb_head, row_main=row_main)
return last_row
[docs]class ReadableWorksheet(object):
"""further for a xlrd.Worksheet"""
[docs] @classmethod
def get_sheet(cls, filepath, sheetname):
"""returns the sheet named sheetname into filepath """
wb = xlrd.open_workbook(filepath)
if sheetname in wb.sheet_names() :
sh = wb.sheet_by_name(sheetname)
else :
sh = None
return sh
[docs] @classmethod
def read_sheet_rows(cls, sh):
"""Reads and returns the sheet rows """
def get_length(row, r, sh):
"""returns length of row (row r of sh) without empty cells"""
for c,cell in enumerate(row) :
if sh.cell_type(r, c) == 0 : # empty
return c
return len(row)
rows = list()
for r in range(sh.nrows):
row = sh.row_values(r)
length = get_length(row, r, sh)
rows.append(row[0:length])
return rows
[docs] @classmethod
def read_sheet_column(cls, sh, ind):
"""Reads in sheet and returns the column ind"""
if ind < sh.ncols :
return sh.col_values(ind)
else :
return None