当前位置: 首页 > 后端技术 > Python

Python常用代码

时间:2023-03-25 22:31:03 Python

1.数据类型1.判断数据类型print(type(json.loads(decode)))2.网络通信1.HTTP通信发送json数据请求importhttp.client,jsonbody=json.dumps({'skill':'IFLYTEK.datetimeX','text':'现在几点'})print("请求问题:"+body)conn=http.client.HTTPConnection('aisopportal.suning.com')conn.request('POST','/aisop-portal/simulation/qa',body)response=conn.getresponse()print("返回状态:"+str(response.status)+""+response.reason)print("返回结果:"+response.read())ifresponse.status==200:result=response.read().decode('utf-8')answer=json.loads(result)['data']['answer']print("响应答案:"+answer)conn.close()2.测试url文件是否存在08/05/N5QEAFs5z0mASVg3AC0v4ZupQbk533.mp3')response=conn.getresponse()ifresponse:exist:code==20'senotexist')3.url解析fromurllib.parseimporturlparseo=urlparse('https://www.baidu.com:8080/s?ie=UTF-8&wd=hello')print('scheme='+o.scheme)print('netloc='+o.netloc)print('host='+o.hostname)print('port='+str(o.port))print('path='+o.path)print('query='+o.query)3.文件目录1.清空目录importosimportshutilshutil.rmtree(dirpath)os.mkdir(dirpath)2.json文件操作#创建json对象#加载json数据3.csv文件操作importcsv#写入数据test,headers=['name','occupation','work']singer1=['刘德华','歌手','忘情水']singer2=['张学友','歌手','狼的传说']rows=[['华健周','歌手','friend'],['周星驰','演员','大内特工']]#encoding指定utf8编码#newline=不会输出隔行与open('test.csv','w',encoding='utf-8',newline='')asf:writer=csv.writer(f)#写入单行数据writer.writerow(headers)writer.writerow(singer1)writer.writerow(singer2)#写入多行数据writer.writerows(rows)#ReadTakethedatatestwithopen('test.csv','r',encoding='utf-8',delimiter=',')asf:reader=csv.reader(f)#指向下一行元素header=next(reader)#打印比文件头低2个元素print(header[1])#打印所有文件头print(header)#Printalldataforrowinreader:print(row)4.打包发布1.安装pyinstallerpipinstallpyinstaller2.安装项目中使用的第三方模块#PyCharm默认下载模块到项目目录(假设项目使用m3u8)pipinstallm3u83。打包文件#当测试可执行文件瞬间关闭时,可以通过命令行运行查看结果。pyinstaller-Ftest_skill.py--hidden-importm3u8#生成的可执行文件位于dist目录test_skill.exe

猜你喜欢