-
Notifications
You must be signed in to change notification settings - Fork 37
/
filestoragemod.py
executable file
·282 lines (221 loc) · 7.8 KB
/
filestoragemod.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# -*- coding: utf-8 -*-
"""
file storage utility
"""
from __future__ import print_function
from builtins import range
import basicSetting
import logging
import os
import os.path
import shutil
import string
from datetime import datetime,date,timedelta
import json
# ///////////////// -- GLOBAL VARIABLES AND INIZIALIZATION --- //////////////////////////////////////////
global DATABASEPATH
DATABASEPATH=basicSetting.data["DATABASEPATH"]
# ///////////////// --- END GLOBAL VARIABLES ------
#-- start DB utility--------////////////////////////////////////////////////////////////////////////////////////
def dbpath(filename):
return os.path.join(DATABASEPATH, filename)
def readfiledata(filename,filedata):
if os.path.isfile(dbpath(filename)): #file is there
# read the selected table file
in_file = open(dbpath(filename),"r")
lines = in_file.readlines()
in_file.close()
del filedata[:]
#print " ln " , lines
for ln in lines:
filedata.append(json.loads(ln))
#print IOdata[0]["name"]
return True
else:
print("----------------------------------------------------------------------> warning no file ", filename)
return False
def readfiledata_full(filename):
if os.path.isfile(dbpath(filename)): #file is there
# read the selected table file
#in_file = open(dbpath(filename),"r")
with open(dbpath(filename)) as json_file:
try:
data = json.load(json_file)
except:
print("not able to parse Json file")
return False
json_file.close()
return data
else:
print("----------------------------------------------------------------------> warning no file ", filename)
return False
def savefiledata_full(filename,filedata):
# questo possibile lista di dizionario: { 'name':'', 'm':0.0, 'q':0.0, 'lastupdate':'' } #variabile tipo dizionario
out_file = open(dbpath(filename),"w")
jsonStr=json.dumps(filedata, sort_keys=True, indent=4)
out_file.write(jsonStr)
out_file.close()
# START Plain text file functions ---------------------------------------- Used for generic file manipulation
def readfiledata_plaintext(pathfilename,filedata): #return list with row of the file
if os.path.isfile(pathfilename): #file is there
# read the selected table file
in_file = open(pathfilename,"r")
lines = in_file.readlines()
in_file.close()
del filedata[:]
for ln in lines:
filedata.append(ln.strip("\n"))
return True
else:
print("---------------> warning no file ", pathfilename)
return False
def savefiledata_plaintext(pathfilename,filedata):
#print "save file ", filedata
try:
out_file = open(pathfilename,"w")
for line in filedata:
out_file.write(line)
out_file.write("\n")
out_file.close()
except:
msg="not able to write file -------->" + pathfilename
print (msg)
def readfiledata_spec(pathfilename,identifier,filedata): # used also in networkdbmod
if os.path.isfile(pathfilename): #file is there
# read the selected table file
in_file = open(pathfilename,"r")
lines = in_file.readlines()
in_file.close()
del filedata[:]
#print " ln " , lines
for ln in lines:
if identifier in ln:
theline=ln[ln.find("{"):ln.find("}")+1]
filedata.append(json.loads(theline))
return True
#print IOdata[0]["name"]
return False
else:
print("------------------------------------------> warning no file ", pathfilename)
return False
def savechangerow_plaintext(pathfilename,searchvalue,newrow): # used to replace row in file giving one string
filedata=[]
readfiledata_plaintext(pathfilename,filedata)
#print "text File /n" , filedata
for i in range(len(filedata)):
line=filedata[i]
if searchvalue in line:
print(" row found ------------ !!!!!!!!! " , line)
filedata[i]=newrow
print(" new row ------------ !!!!!!!!! " , newrow)
savefiledata_plaintext(pathfilename,filedata)
return True
return False
def readvalue_plaintext(pathfilename,key,separation): # used to get data from text file
#format of the row "key:value"
filedata=[]
readfiledata_plaintext(pathfilename,filedata)
for line in filedata:
if key in line:
substr=line.split(separation)
if len(substr)>1:
value=substr[1].strip()
return value
return False
# END Plain text file functions ---------------------------------------- Used for generic file manipulation
def disct2text(dictdata):
return json.dumps(dictdata, sort_keys=True)
def savefiledata(filename,filedata):
# questo possibile lista di dizionario: { 'name':'', 'm':0.0, 'q':0.0, 'lastupdate':'' } #variabile tipo dizionario
out_file = open(dbpath(filename),"w")
for line in filedata:
#jsonStr=json.dumps(line, sort_keys=True, indent=14)
jsonStr=json.dumps(line, sort_keys=True)
#print ( " Jsonstring ", jsonStr)
out_file.write(jsonStr)
out_file.write("\n")
out_file.close()
def appendfiledata(filename,filedata):
# questo il possibile dizionario: { 'name':'', 'm':0.0, 'q':0.0, 'lastupdate':'' } #variabile tipo dizionario
out_file = open(dbpath(filename),"a")
for line in filedata:
jsonStr=json.dumps(line)
out_file.write(jsonStr)
out_file.write("\n")
out_file.close()
def savechange(filename,searchfield,searchvalue,fieldtochange,newvalue):
filedata=[]
readfiledata(filename,filedata)
# questo il possibile dizionario: { 'name':'', 'm':0.0, 'q':0.0, 'lastupdate':'' } #variabile tipo dizionario
for line in filedata:
if searchfield in line:
if line[searchfield]==searchvalue:
line[fieldtochange]=newvalue
savefiledata(filename,filedata)
return True
return False
def replacewordandsave(filename,oldvalue,newvalue): #oldvalue and newvalue are lists
filedata=[]
readfiledata(filename,filedata)
# questo il possibile dizionario: { 'name':'', 'm':0.0, 'q':0.0, 'lastupdate':'' } #variabile tipo dizionario
for line in filedata:
for key in line:
for i in range(len(newvalue)): #iterate in the lists
if newvalue[i]!=oldvalue[i]:
if line[key]==oldvalue[i]:
line[key]=newvalue[i]
savefiledata(filename,filedata)
return True
def deletefile(filename):
try:
os.remove(dbpath(filename))
return True
except OSError:
return False
def copydbfileto(filename,dst):
try:
copyfile(dbpath(filename), dst)
return True
except OSError:
return False
# utility functions --------------------------------------
def searchdata(filename,recordkey,recordvalue,keytosearch):
IOdata=[]
readfiledata(filename,IOdata)
for ln in IOdata:
if recordkey in ln:
if ln[recordkey]==recordvalue:
if keytosearch in ln:
return ln[keytosearch]
return ""
def searchdatalist(filename,recordkey,recordvalue,keytosearch):
IOdata=[]
readfiledata(filename,IOdata)
datalist=[]
for ln in IOdata:
if recordkey in ln:
if ln[recordkey]==recordvalue:
if keytosearch in ln:
datalist.append(ln[keytosearch])
return datalist
def getfieldinstringvalue(filename,fielditem,stringtofind,valuelist):
IOdata=[]
readfiledata(filename,IOdata)
del valuelist[:]
for line in IOdata:
name=line[fielditem]
if name.find(stringtofind)>-1:
valuelist.append(name)
#--end --------////////////////////////////////////////////////////////////////////////////////////
if __name__ == '__main__':
FILENAME='dummy.txt'
data=[
{"lastupdate": "", "name": "ECsensor1", "pin": 7, "m": 1.0, "controllercmd": "", "q": 0.0, "IOtype": "di"},
{"lastupdate": "", "name": "ECsensor1enable", "pin": 4, "m": 1.0, "controllercmd": "", "q": 0.0, "IOtype": "do"},
{"lastupdate": "", "name": "PHsensor1", "pin": 0, "m": 1.0, "controllercmd": "5", "q": 0.0, "IOtype": "ai"}
]
savefiledata(FILENAME,data)
savechange(FILENAME,"name","ECsensor1","q",2.0)
filedata=[]
readfiledata(FILENAME,filedata)
print(filedata)