python小随笔

python json相关小随笔

json数据解析成字符串

json.dumps序列化时候对中文默认使用的ascii编码,想要输出真正的中文需要指定ensure_ascii=False

data="{\"dataType\": \"text\",\"field\": \"出生日期\"}"
json_data = json.dumps(data,ensure_ascii=False)
print(json_data)
#未添加ensure_ascii=False輸出結果  "{\"dataType\": \"text\",\"field\": \"\u51fa\u751f\u65e5\u671f\"}"
#添加ensure_ascii=False後輸出結果 {\"dataType\": \"text\",\"field\": \"出生日期\"}"

python连接数据库(mysql)

def savesomething(url,username,password,schema):
    import os
    #本地是
    #import MySQLdb
    #线上是
    import pymysql
    # 连接数据库 url username用户名 password:密码 schema:数据库名
    db = pymysql.connect(url,username, password, schema, charset='utf8' )
    cursor = db.cursor()
    try:
        cursor.execute("sql") # 运行sql
        db.commit()
    except:
        db.rollback() # 出现异常回滚

    db.close() #关闭连接

json文件读写

def json_dump(file_path, obj):
  print('json_dump params: ', file_path, obj)
  # with open(file_path, 'w') as f:
  #     json.dump(obj, f)
  #     f.close()
  # 支持中文解析
  import io
  with io.open(file_path, 'w',encoding='utf-8') as f:
      # json.dump(obj, f)
      f.write(unicode(json.dumps(obj, ensure_ascii=False)))



def json_load(file_path):
  print('json_load params: ', file_path)
  # f = open(file_path, 'r', encoding='utf-8')
  # jsonObj= json.load(f)
  # print(jsonObj)
  # f.close()
  # return jsonObj
  # 支持中文解析
  import io
  jsonObj = None
  with io.open(file_path, 'r', encoding='utf-8') as f:
      jsonObj= json.load(f, encoding='utf-8')
      print(jsonObj)
  return jsonObj

python中for循环

(第一次见到这种写法觉得厉害再此处记录)

list11=["a","b","c"]

outputs = [
    x
    for x in list11 if x=="a"# 此处可以直接添加条件
]
print(outputs )
#打印结果['a']

python 判断非空的几种方式

if where is None or where==’’:
if not add_mode_value.strip():
if where.strip() != “”:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值