Python常用函数
Request
import requests
def send_withParam(p1,p2):
#url,{}为字符串占位符
url = 'http://localhost:80/platform/getCameraUrl'.format("")
#http参数
payload = {
"param1": p1,
"param2": p2
}
#http请求头
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
'Cookie': 'JSESSIONID=XXXX'
}
#发送请求
res = requests.get(url, params=payload, headers=headers)
return res;
res = send_withParam('1','2');
print(res.text);
文件读写
open写文件
#传统模式,不够安全,需要手动关闭文件资源
#如果在关闭文件之前程序异常终止,
#被打开的文件不能被关闭,占用系统资源
f = open('newFile1.txt','w')
f.write('这种模式写入不够安全,请慎用')
f.close()
#推荐模式,即使程序异常终止
#也会自动关闭文件
#类似于 try catch
with open('newFile2.txt','w') as f:
f.write('推荐使用这种模式')
#内容追加模式
with open('newFile2.txt','a') as f:
f.write('不会覆盖已有内容')
open读文件
#读文件,一次性读所有内容,适用文件大小较小
with open('newFile1.txt','r') as f:
print(f.read())
#读文件,循环读,每次只读指定大小的内容,适用文件大小较大
with open('newFile1.txt','r') as f:
while True:
print(f.read(2))
# 打开GBK文件
with open('newFile1.txt','r',encoding='gbk') as f:
print(f.read())
#按行读取内容
with open('newFile1.txt','r') as f:
for line in f.readlines():
print(line)
日期时间
遍历起止日期
import datetime
def main():
begin = datetime.date(2014,6,1)
end = datetime.date(2014,6,7)
for i in range((end - begin).days+1):
day = begin + datetime.timedelta(days=i)
print(day)
if __name__ == '__main__':
main()
分钟遍历(不能跨天)
# 导入datetime库
import datetime
# 创建开始时间点和结束时间点
d1 = datetime.datetime(2022,4,27,0,0,0)
d2 = datetime.datetime(2022,4,27,23,59,59)
# 获取时间间隔
delta = d2 - d1
# 遍历获得每一个时间点(分钟)
for i in range(delta.seconds + 1):
if i%60 == 0:
print(d1 + datetime.timedelta(seconds = i))
秒遍历(跨天)
import datetime
d1 = datetime.datetime(2022,4,24,0,0,0)
d2 = datetime.datetime(2022,4,27,23,59,59)
# 获取时间间隔
delta = d2 - d1
# 遍历天数
for d in range(delta.days+1):
# 遍历时间秒(最大为二十四小时的秒数)
seconds = range(delta.seconds + 1);
for s in seconds:
# 每5s进入执行一次
if s%5 == 0:
# 设置开始天
beginDay = d1 + datetime.timedelta(days=d);
# 设置起始时间
start = beginDay + datetime.timedelta(seconds = s);
end = beginDay + datetime.timedelta(seconds = s+5);
#打印在控制台中
print(start,end);
如果这篇文章对你有用,可以关注本人微信公众号获取更多ヽ(^ω^)ノ ~
![微信公众号二维码](https://images.cnblogs.com/cnblogs_com/aeolian/1679458/o_wechat_gzh_qrcode.jpg)