這是個人在專案中抽取的**,自己寫的utils的通用模組,使用的框架是tronado,包括了檔案的讀寫操作,api格式的統一函式,如有特別需要可以聯絡我或者自己擴充套件,剛學python不久,僅供參考,例子如下。
importtime
import
json
import
logging
import
traceback
import
codecs
import
osconf_log =logging
def resp_dict(data='', status="
success
", message="
successful"):
"""return a dict format response
"""return dict(status=status, message=message, data=data, timestamp=time.time())
defread_json(filename):
#load data from file
content =
try:
conf_log.info(
"reading input from file:
" +str(filename))
ifos.path.exists(filename):
with open(filename, "r
") as fp:
content =json.load(fp)
else
: conf_log.warning(
"file %s does not exist.
" %filename)
except
exception as e:
conf_log.error(e)
ex_str =traceback.format_exc()
conf_log.error(ex_str)
return
content
defread_json_config(filename, def_res):
#load data from file
content =def_res
try:
conf_log.info(
"reading input from file:
" +str(filename))
ifos.path.exists(filename):
with open(filename, "r
") as fp:
content =json.load(fp)
else
: conf_log.warning(
"file %s does not exist.
" %filename)
except
exception as e:
conf_log.error(e)
ex_str =traceback.format_exc()
conf_log.error(ex_str)
return
content
defwrite_json(j_dict, file_name):
#dump data into file
try:
conf_log.info(
"writing file:
" +str(file_name))
with codecs.open(file_name, "w
", "
utf-8
") as outputfile:
json.dump(j_dict, outputfile, ensure_ascii=false, encoding="
utf-8")
except
exception as e:
conf_log.error(e)
ex_str =traceback.format_exc()
conf_log.error(ex_str)
with codecs.open(file_name, "w
", "
utf-8
") as outputfile:
outputfile.write(str(j_dict))
Python檔案讀寫常見用法總結
usr bin env python coding utf 8 檔案讀取三步驟 1.開啟檔案 f open file,mode r buffering none,encoding none,errors none,newline none,closefd true mode r,w,a,b,2.操作...
Python檔案讀寫常見用法總結
1.讀取檔案 usr bin env python coding 程式設計客棧utf 8 檔案讀取三步驟 1.開啟檔案 f open file,mode r buffer程式設計客棧ing none,encoding none,errors none,newline none,closefd tru...
python檔案讀寫出現亂碼總結
1.錯誤的開啟方式 coding utf 8 f open test.txt w f.write m ars is slim,isn he?n 火星教 print f.read f.close 控制台結果 2.正確的開啟方式 建議在進行寫入操作後先將檔案關閉,然後再開啟,最後再讀取檔案 若你的txt...