How To/python/MyMiscUtils/

VERY IMPORTANT NOTE!!!

Remember THIS IS NOT CSV READER/WRITER! For reading/writing CSV files use python's csv module!

# -*- coding: utf-8 -*-
 
"""
writeListAsFile(lst, file, sep = '', mode = "w") -> void
 
save list 'lst' as file 'file'.
If list item is list, dict or tuple 'sep' separator is used to separate values.
Only 2-dimensional lists are supported.
 
Ff you want to append lines to file instead of clearing it use 'a' mode instead
of default 'w'
"""
 
def writeListAsFile(lst, file, sep = '', mode = "w"):
    """ write list to file """
    f = open(file, mode)
    for i in lst:
        if isinstance(i, list) or isinstance(i, tuple) or isinstance(i, dict):
            f.write(sep.join([str(x) for x in i]))
        else:
            f.write(str(i))
        f.write('\n')
    f.close()
###/writeListAsFile
 
 
"""
readFileToList(file, sep=',', alwaysList = True) -> list
function reads file and returns list.
if "alwaysList" is set to True (default) one-element row are returned as
one-element lists. If "alwaysList" is set to False one-element rows are
retyrned as strings. Eg.:
#file.txt
1
2
3,4,5
 
print readFileToList("file.txt", ',', True)
#[['1'],['2'],['3','4','5']]
 
print readFileToList("file.txt", ',', False)
#['1','2',['3','4','5']]
 
Second option is useful when you are using one-value-per-row files, eg.:
 
#names.txt
Smith
Anderson
Black
"""
def readFileToList(file, sep=',', alwaysList = True):
    """ read file to list """
    out = []
    f = open(file)
    while 1:
        line = f.readline()
        if not line: break
        tmp = line.strip()
        if tmp != '':
            tmp = tmp.split(sep)
            if alwaysList or len(tmp) > 1:
                out.append(tmp)
            else:
                out.append(tmp[0])
    f.close()
    return out
###/readFileToList
 
 
"""
returns eg.{
readFileToDict(file, sep=';', idx = 0) -> dict
'a1':['a1','a2','a3'],
'b1':['b1','b2','b3'],
}
"""
def readFileToDict(file, sep=';', idx = 0):
    """ read file to dict """
    out = {}
    f = open(file)
    while 1:
        line = f.readline()
        if not line: break
        if line.strip() != '':
            tmp = line.strip().split(sep)
            out[tmp[idx]] = tmp
    f.close()
    return out
###/readFileToDict
 
 
"""
read2colFileToDict(file, sep=';', asKey = 0) -> dict
Make sure that file has 2 columns separated with 'sep' separator. asKey stands
for which column have to be treated as key. 0 for column 1, and any other for
column 2. Eg.:
 
#colors.txt
f00:red
000:black
f90:orange
fff:white
 
print read2colFileToDict('colors.txt', ':', 1)
#{'red':'f00','black':'000','orange':'f90','white':'fff'}
"""
def read2colFileToDict(file, sep=';', asKey = 0):
    """ read file to dict """
    if asKey == 0:
        asKey = 0
        asVal = 1
    else:
        asKey = 1
        asVal = 0
    out = {}
    f = open(file)
    while 1:
        line = f.readline()
        if not line: break
        if line.strip() != '':
            tmp = line.strip().split(sep)
            out[tmp[asKey]] = asVal
    f.close()
    return out
###/read2colFileToDict