2019년 2월 23일 토요일

[Python] File Library Wrappers (File, Directory, Base64, Json, Zip)


pyfile.py


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
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import codecs
import os

######################################################################
# File and Directory Library
######################################################################
def filePeek(f):
    pos = f.tell()
    line = f.readline()
    f.seek(pos)
    return line    

def fileExists(file_path):
    return os.path.exists(file_path)

def fileToString(file):
    f = codecs.open(file, "r", "utf-8")
    text = f.read()
    f.close()
    return text

def stringToFile(file,data):
    f = codecs.open(file, "w", "utf-8")
    f.write(data)
    f.close()

def fileToBinary(file):
    f = open(file, "rb")
    data = f.read()
    f.close()
    return data;
    
def binaryToFile(file,data):
    f = open(file, "wb")
    f.write(data)
    f.close()
    
def searchFile(dirname, recurse=False, extensions=None):
    list = []
    filenames = os.listdir(dirname)
    for filename in filenames:
        full_filename = os.path.join(dirname, filename)
        if os.path.isdir(full_filename) and recurse == True:
            list += searchFile(full_filename, recurse=recurse, extensions=extensions)
        if os.path.isfile(full_filename):
            ext = os.path.splitext(filename)[1]
            if extensions is None or ext in extensions:
                list.append(full_filename)
    return list

def walkDir(dirname,extensions):
    list = []
    for (path, dirs, files) in os.walk(dirname):
        print( path, dirs, files )
        for filename in files:
            ext = os.path.splitext(filename)[-1]
            if ext in extensions:
                list.append(os.path.join(path, filename))
    return list

######################################################################
# base64 Library
######################################################################
import base64

def fileToBase64(filepath):
    fp = open(filepath, "rb")
    data = fp.read()
    fp.close()
    return base64.b64encode(data).decode('utf-8')

def stringToBase64(s):
    return base64.b64encode(s.encode('utf-8'))

def base64ToString(b):
    return base64.b64decode(b).decode('utf-8')

######################################################################
# JSON Library
######################################################################
import json

def pythonToJson(s):
    return json.dumps(s, indent=4) #return str

def jsonToPython(s):
    return json.loads(s)           #return dict

######################################################################
# ZIP Library
######################################################################
import zipfile

def checkZip(filename):
    return zipfile.is_zipfile(filename)

class pyzip():
    def __init__(self,filename,create=None):
        if create is None:
            if filename is not None and zipfile.is_zipfile(filename) == True:
                self.zf = zipfile.ZipFile(filename)
        else:
            self.zf = zipfile.ZipFile(filename, mode='w')

    def close(self):
        self.zf.close()
        
    def namelist(self):
        return self.zf.namelist()
    
    def infolist(self,filename):
        return self.zf.infolist()

    def extract(self,inname,outfile):
        data = self.zf.read(inname)
        binaryToFile(outfile,data)

    def add(self,filename):
        self.zf.write(filename)
        
    def dump(self):
        for info in self.zf.infolist():
            print( "%20s: %s" % ('name', info.filename) )
            print( "%20s: %s" % ('org_size', info.file_size) )
            print( "%20s: %s" % ('cmp_size', info.compress_size) )
            print( "%20s: %s" % ('modified', info.date_time) )
        print( "Total: %d" % (len(self.zf.infolist())))
        
        
######################################################################
# Test Code
######################################################################
def pythonToJsonTest():
    customer = {
        'id': 152352,
        'name': 'alice',
        'history': [
            {'date': '2015-03-11', 'item': 'iPhone'},
            {'date': '2016-02-23', 'item': 'Monitor'},
        ]
    }
    jsonString = pythonToJson(customer)
    print(jsonString)
    print(type(jsonString))  # class str

def jsonToPythonTest():
    jsonString = '{"name": "alice", "id": 152352, "history": [{"date": "2015-03-11", "item": "iPhone"}, {"date": "2016-02-23", "item": "Monitor"}]}'
    dict = jsonToPython(jsonString)
    print(dict['name'])
    for h in dict['history']:
        print(h['date'], h['item'])
    
def zipTest():
    z = pyzip('D:/Temp/a.zip')
    z.dump()
    z.extract('pyshell_demo.py','D:/Temp/pyshell_demo.py_zipout')
    z2 = pyzip('D:/Temp/b.zip', create=True)
    z2.add('D:/Temp/aa.py');
    z2.close()

    
######################################################################
# Main
######################################################################
if __name__ == "__main__":
    #list = walkDir("D:/Temp", extensions= ['.py','.png'])
    #print ( len(list), list)
    #print(fileToBase64("D:/Temp/line.png"))
    #pythonToJsonTest()
    #jsonToPythonTest()
    zipTest()


댓글 없음:

댓글 쓰기