解包:

# mag = "admin,123123"
# print(mag.split(','))
# username,password = mag.split(',')
# print(username)
# print(password)

l =[1,2,3]
l2=(1,2,3)
l3='abc'
f, s, d = l #只要有下标的都可以这样取值
print(f, s, d)

d = {"username":"admin","password":"123123"}
print(d.items()) #把字典转成二维数组list
#dict_items([('username', 'admin'), ('password', '123123')])
for k,v in d.items():
    print(k)
    print(k,v)

 

文件操作:

#r+      w+     a+
#rb      wb     ab      #   b二进制模式
#rb+     wb+    ab+
#读写   写读   追加读模式
#1、r相关,文件不存在的时候报错FileNotFoundError,指针在最前面,覆盖最前面的
#         如果写的话要把指针移到最后面
#2、w相关,重新创建文件,清空文件内容
#3、a相关,读的话要移动指针f.seek(0),不管怎么移动指针,追加时都在文件末尾追加
#         文件不存在会创建


#1、r+,不能写,文件不存在的时候报错FileNotFoundError
#2、w+,不能读
#3、a+,不能读
# f = open('user.txt','r+')
# f.writelines("n2")
# f.flush()#刷新缓存区,让数据立刻写到磁盘上
# f.tell()#指针的位置
# result = f.read()
# f.close()
# print(result)

# f = open('access.log','r+')
# for line in f: #循环文件对象就是循环文件的每一行
#     print(line)
# f.close()


#修改文件
# f = open(r'C:\Users\李家强\PycharmProjects') #r原字符,不需要转义


# f = open("user.txt",'a+',encoding="utf-8")
# f.seek(0)
# result = f.read()
# result_new = result.replace("hello","你好")
# f.seek(0)
# f.truncate() #清空文件
# f.write(result_new)
# f.close()

import os
f1 = open("user.txt",encoding='utf-8')
f2 = open("user.txt.bak","w",encoding="utf-8")
for line in f1:#循环文件对象就是循环文件的每一行
    new_line = line.replace("","周杰伦")#替换
    f2.write(new_line)#写入新的
f1.close()
f2.close()
os.remove("user.txt")#删除
os.rename("user.txt.bak","user.txt")#改名成user.txt



#自动关闭文件
with open("user.txt",encoding='utf-8') as f,open("user2.txt",encoding='utf-8') as f2:
    for line in f1:
        new_line = line.replace("", "周杰伦")
        f2.write(new_line)
os.remove("user.txt")
os.rename("user2.txt", "user.txt")

 

json模块:

import json
import pprint
# python的数据类型转json:    json.dumps
# d = {"code":0,"msg":"操作成功","token":"xxxx"}
# pprint.pprint(d)
# json_str = json.dumps(d,ensure_ascii=False)#unicode显示中文
# pprint.pprint(json_str)#unicode

# json的数据类型转python:    json.loads
# json_str = '{"code":0,"msg":"操作成功","token":"xxxx"}'
# dic = json.loads(json_str)
# pprint.pprint(dic)


# with open("user.txt",encoding='utf-8') as f:
#     d = json.loads(f.read())
#     print(d)


d = {"code":0,"msg":"操作成功","token":"xxxx"}
# with open("user.json",'w',encoding='utf-8') as f:
#     json_str = json.dumps(d,ensure_ascii=False,indent=4)#indent格式
#     f.write(json_str)

#load 自动读 不用写read
with open("user.txt",encoding='utf-8') as f:
    result = json.load(f)
    print(result)

#dump 自动写 不用write
with open("user.txt",encoding='utf-8') as f:
    json.dump(d,f,ensure_ascii=False,indent=4)

 

监控日志练习:

import time
FILE_NAME = 'access.log'
point = 0
while True:
    ips = {}
    f = open(FILE_NAME,encoding='utf-8')
    f.seek(point)
    if point==0: #判断是否为第一次读取
        f.read()
    else:
        for line in f:
            line = line.strip()
            if line:
                ip = line.split()[0]
                if ip in ips:
                    ips[ip] +=1
                else:
                    ips[ip] = 1
    point = f.tell()
    f.close()
    for ip,count in ips.items():
        if count>=50:
            print("加入黑名单的ip是 %s" % ip)
    time.sleep(60)

 

函数:

#函数、方法
#提高代码复用,简化代码

#定义函数
# #      没有写return: 返回值none
# def hello():
#     print('hello')
# #调用函数  ,才会执行
# # hello()
# print(hello())

#   return多个值,返回有值
# def welcome(name,age="13"):
#     return name,age
#     print("welcome %s,you are from %s"%(name,age))
# print(welcome("lee"))
# print(welcome("li","14"))

#   return空,返回none
# def test():
#     return
# print(test())

def op_file(filename,content=None):
    with open(filename,'a', encoding='utf-8') as f:
        f.seek()
        if content:
            f.write(content)
        else:
            result = f.read()
            return result
def is_float(s):
    s = str(s)
    if s.count('.') == 1:
        left, right = s.split('.')  # [1,1]#-s.2
        if left.isdigit() and right.isdigit():
            return True
        elif left.startswith('-') and left.count('-') == 1 \
                and left[1:].isdigit() and right.isdigit():
            return True

    return False

 

函数参数:

def send_sms(*args):#可选参数,接受的是一个元祖 *args
    print(args)
send_sms()
send_sms(2)
send_sms(2,3,4,5,6,'o')


def send_sms(**kwargs):#关键字参数,接受的是一个字典 **kwargs
    print(kwargs)
send_sms()
send_sms(a = 2)
send_sms(a=2,b=3,c=4,d=5,e=6,f='o')

 

全局变量:

# a = 100  # 全局变量
# def test():
#     global a  #global声明改的是全局变量a=1,写代码时少用全局变量
#     a =1
#     print(a)
#
# test()
# print(a)

#
# def test():
#     global a
#     a = 5
#
#
# def test1():
#     c = a + 5
#     return c
# # test()
# res = test1()
# print(res)


# 循环里 return==break

 

递归:

#函数自己调用自己,就是递归

# def test():
#     number = input("请输入一个数字:").strip()
#     number = int(number)
#     if number %2 == 0:
#         print("输入正确")
#         return
#     test()
# test()

def replace(src,old,new):
    if old in src:
        return new.join(src.split(old))
    return src

a = 'abc,abc,sdgsd,' #[abc你好abc你好sdgsd你好]
b = "123"
c = "你好"

result = replace(a,b,c)
print(result)

 

posted on 2021-05-09 17:41  python测开搬砖人  阅读(57)  评论(0编辑  收藏  举报