PYTHON自动化Day5-文件修改,函数,全局变量,json和字典转换,函数不固定参数,递归,random函数

#为了避免频繁的和磁盘交互,内存会把需要和磁盘交互的内容先放入缓冲区,缓冲区满了写入磁盘
# fw = open('username','w')
# fw.write('hhhh')
# fw.flush()  #强制把缓冲区里面的数据写到磁盘上
write和writelines的区别:
#
f.write() 只能写字符串 #f.writelines() #会帮我们循环一次,如果传string也可以写入,但是他会循环一次,效率不高 a=[123,456] for i in a : f.write(i) #等同于 f.writelines(a)

笔记:

#函数、
内置函数
python自带的一些函数,直接拿过来能用的
id() #看内存地址
type() #看数据类型
print() #打印
input() #输入
list() #转list
set()# 转集合
str()#转字符串
dict()#转字典
int()#转int
float()#转float类型
len()#取长度
max()
min()
dir() #帮助你的
sorted()#排序
round(11.00011,2)#保留几位小数
map() #下周
filter() #下周
zip() #下周

#函数:
函数、方法、功能
1、提高代码的复用性
2、让代码更简洁、简化代码
必填参数、默认值参数
#局部变量
函数里面定义的变量,都是局部变量,只能在函数里面用,出了函数之后就不能用了。
#全局变量
公共的变量,都可以用的变量。
1、不安全,因为所有人都可以改
2、全局变量它会一直占着内存
#return
1、把函数处理的结果返回回来
2、结束函数,函数里面遇到return,函数会立即结束
#常量
#一个不变的值
#如果你写了一样功能,那你就要想是不是能把这个功能封装成一个函数
递归:
函数自己调用自己。
模块:
模块其实就是一个python文件
1、标准模块、标准包
#python自带的这些模块,直接import就能用的
import string,random,datetime,os,json
2、第三方模块,别人写好的一些模块,你要安装之后才可以用
#1、傻瓜式的
pip install pymysql
1、没有pip命令的怎么搞:
1、pycharm里面点python console
2、找到python安装目录
3、然后把安装目录下的scripts目录,加入到环境变量里面即可
ps:环境变量在PATH里面加
2、Unknown or unsupported command 'install' 出来这个问提怎么解决
1、打开 C:strawberryperlin
2、把这个目录下的pip 都改成其他的名字,这个对其他的没有影响
#2、手动安装
1、whl结尾的安装包
pip install redis-2.10.6-py2.py3-none-any.whl
2、.tar.gz结尾的安装包
1、解压这个压缩包
2、进入到这个解压之后的文件夹里面
3、在命令行里面运行 python setup.py install

3、自己写的python文件

一.文件修改

#1、简单粗暴直接
#  1、打开一个文件,获取到他的所有内容
#  2、对内容进行修改
#  3、清空原来文件的内容
#  4、把新的内容写进去
#syz_niuhanyang,78910
syz_zll,78910
syz_fyr,78910
f = open('username','a+',encoding='utf-8')
f.seek(0)
all_str = ''
for s in f:
    new_s ='syz_'+s
    all_str=all_str+new_s
f.seek(0)
f.truncate() #清空文件内容
f.write(all_str)
f.close()
#2.第二种方法:
#打开2个文件
# a文件
# 写一行写到b文件
# 删掉a文件,b文件名字改成a文件名
# flower
import os
with open('words',encoding='utf-8') as fr,open('.words.bak','w',encoding='utf-8') as fw:
    for line in fr:
        new_line = line.replace('','flower')
        fw.write(new_line)
os.remove('words') #删除文件
os.rename('.words.bak','words') #改名

二.函数:

def say(): #函数名
    print('hello')#函数体
#函数不调用是不会被执行的
# say()  #调用函数
#函数的参数
def calc(a,b):  #形参, 形式参数  #位置参数,必填参数
    res = a * b
    print('%s * %s = %s'%(a,b,res))

# calc(7,8)  #实参,实际参数
def op_file(file_name,conent=None):
    #默认值参数,它是非必填的
    f = open(file_name,'a+',encoding='utf-8')
    f.seek(0)
    if conent:#不为空代表写
        f.write(conent)
        f.flush()
    else:
        all_users = f.read()
        return all_users  #调用完函数之后,返回什么结果
    f.close()
# res = op_file('a.txt')
# print(res)
def haha():
    #函数里面遇到return函数就立即结束了
    for i in range(5):
        print(i)
        if i==3:
            return  #只写一个return的话,就返回None
# res = haha()
# print(res)
import string
def check(pwd):
    #长度6-11
    #字母和数字吧
    if len(pwd)>5 and len(pwd)<12:
        if set(pwd) & set(string.ascii_letters) and set(pwd) & set(string.digits):
            print('密码合法')
        else:
            print('密码不合法')
    else:
        print('密码不合法')
# res = check('asd1234')  #函数里面如果没有return的话,默认返回None
# print(res)
# l = [1,6,8,2,4,8,9]
# print(l.sort())
# print(l)
def is_float(s):
    s = str(s)
    if s.count('.')==1:#小数点个数
        s_list = s.split('.')
        left = s_list[0]  #小数点左边
        right = s_list[1] #小数点右边
        if left.isdigit() and right.isdigit():  #正小数
            return True
        elif left.startswith('-') and left.count('-')==1 and 
                left.split('-')[1].isdigit() and 
                right.isdigit():  #判断合法负小数
                return True
    return False


# 1.98
# -2.50
# retrun True
# retrun False
# 1.98
# 1.98.23
# -1.90
#  需求分析:
    #1、 小数点个数  .count()
    # 2、按照小数点进行分割  1.98  [1,98] s.87  98.s1
    #3、正小数:小数点左边是整数 右边也是整数 .isdigits()
    #   负小数:小数点左边是以负号开头,但是只有一个负号,右边也是整数  -9.85

money = 500

def test(consume): # 500
    return money - consume

def test1(money):
    return test(money) + money

money = test1(money)
print(money)

三.全局变量,函数调用传参方法

name = '谢红'
#全局变量
#如果要改全局变量的话,那你要先声明一下,你修改值是全局变量
def sayName():
    global name
    name = '刘伟'
    print('name1',name)
def lw():
    age = 28
    return age

def setName():
    global name
    name = '摸手哥'
sayName()
setName()
print('name2',name)

def op_mysql(host,port,username,password,db,charset,sql):
    print('连接数据库')
#第一种方法调用,按照顺序传入参数
op_mysql(
    '192.168.1.1',
    3306,'root','123456','jxz','utf-8','select')
#第二种方法调用,制定形参名传实参,顺序就可以任意了
op_mysql(sql='select * from user;',
         host='192.158.11.1',
         username='sdfdsfs',
         password='sdf',
         db='sdfsdf',
         charset='sdfsdf',
         port='xx'
         )

#可以第一种和第二种方法混合使用
op_mysql(
    '192.168.1.1',
    db='sfsdf',
    charset='sdfsdf',
    sql='select * from user;'
         )

四.json和字典的相互转换

import json
#json串是一个字符串
#json串转为字典
f = open('product.json',encoding='utf-8')
res = f.read()
product_dic = json.loads(res)  #把json串,变成python的数据类型,注意这里为loads,需要先读出来然后传给他
#json.load 如果用这个load不需要先把文件中内容读出来,直接传f给他,就会自动读文件出来
print(json.load(f)) #传一个文件对象,它会帮你读文件


#字典转json
d =  {
    'zll':{
        'addr':'北京',
        'age':28
    },
    'ljj':{
        'addr':'北京',
        'age':38
    }
}
#把字典转为json,写入文件
fw = open('user_info.json','w',encoding='utf-8')
#ensure_ascii=False 可以写入中文
#indent=4 自动缩进
dic_json = json.dumps(d,ensure_ascii=False,indent=4)  #字典转成json,字典转成字符串,因为json其实就是字符串,只是有一定格式
fw.write(dic_json)

#下面这一行可以替代上面两行,用dump方法,传入fw 就可以直接写入文件了
json.dump(d,fw,ensure_ascii=False,indent=10)  #操作文件

小练习:

import json
def op_data(filename,dic=None):
    if dic:#写入进去
        with open(filename,'w',encoding='utf-8') as fw:
            json.dump(dic,fw,ensure_ascii=False,indent=4)
    else:
        with open(filename,encoding='utf-8') as fr:
            return json.load(fr)
FILE_NAME = 'user_info.json'
all_users = op_data(FILE_NAME)
for i in range(3):
    choice = input('输入,1注册,2、删除')
    if choice=='1':
        username = input('usenrame:')
        pwd = input('pwd:')
        if username not in all_users:
            all_users[username]=pwd
            op_data(FILE_NAME,all_users)


    elif choice=="2":
        username = input('usenrame:')
        all_users.pop(username)
        op_data(FILE_NAME, all_users)

五:函数不固定参数

def syz(*args):  #参数组。不限制参数个数,不传也可以,如果前面还有必填参数,各个参数依次后延
    # print(a)
    username = args[0]
    pwd = args[1]
    age = args[2]
syz('niuhanyang','2423',2323,1)
# syz('1s','sdf')
def syz2(time,**kwargs):  #关键字参数, 传入的必须是字典类型的key=value
    print(kwargs)

# syz2()  #没有传time会报错
syz2('sdf') #当没有time时,会报错,因为没有value
syz2(name='nhy',age=38,time='20180912')
syz2('2018',name='nhy',age=38,addr='回龙观',home='河南')
syz2(time='xx',xx='xxx')

六,递归

#自己调用自己

def test1():
    num = int(input('please enter a number:'))
    if num%2==0:#判断输入的数字是不是偶数
       return True #如果是偶数的话,程序就退出了,返回true
    print('不是偶数请重新输入!')
    return test1()#如果不是偶数的话继续调用自己,输入值
print(test1())#调用test

#少用递归,递归最多递归999,递归的效率不高。
i = 0
def test():
    global i
    i+=1
    print(i)
    test()
test()

六.random函数

import random,string
print(string.printable) #代表 数字+字母+特殊字符

print(random.randint(1,10)) #随机取整数
print(round(random.uniform(1,99),2))#随机小数
print(random.choice([1,2,3,4])) #只能随机取1个元素
print(random.sample(string.printable,5)) #随机取N个元素,返回的是list
#洗牌
pickts = ['A','J','Q','K',2,3,4,5,6]
random.shuffle(pickts) #只能传list
print(pickts)

作业:

1、双色球的
红球是 1-33 6
篮球 1-16 1
输入几,就产生多少条
随机数,random

import random

def seq():
    red_num = [] #红球
    while len(red_num)!=6:
        # 1 - 33
        num = random.randint(1,33)
        num = str(num).zfill(2)
        if num not in red_num:
            red_num.append(num)
    blue_num = str(random.randint(1,16)).zfill(2)
    red_num_str = ' '.join(red_num)
    res = '篮球是 %s 红球是 %s
'%(blue_num,red_num_str)
    return res

def write_file(l):
    with open('seq.txt','w',encoding='utf-8') as fw:
        fw.writelines(l)

def main():
    all_res = [] #存所有结果的
    num = input('请输入你要产生多少条:').strip()
    if num.isdigit():
        num = int(num)
        while num != len(all_res):
            res = seq()
            if res not in all_res:
                all_res.append(res)
    else:
        print('条数只能是整数!')
    write_file(all_res)
main()

2、添加商品
1、添加 商品名称 价格 颜色 数量
2、查看商品信息
3、删除
4、修改 商品名称 价格 颜色 数量
5、操作文件

import json

FILE_NAME = 'goods.json'
def op_file(name,content=None):
    if content:
        with open(name,'w',encoding='utf-8') as fw:
            json.dump(content,fw,indent=4,ensure_ascii=False)
    else:
        with open(name,encoding='utf-8') as fr:
            res = json.load(fr)
            return res
all_goods = op_file(FILE_NAME)

def check_price(price):
    price = str(price)
    if price.isdigit():
        price = int(price)
        if price>0:
            return True
    else:
        if price.count('.')==1:
            tmp = price.split('.')
            #0.0
            left = tmp[0]
            right = tmp[1]
            # 1.00

            if left.isdigit() and right.isdigit() and int(right)>0:  #1.0
                return True
            elif left.isdigit() and right.isdigit() and int(left)>0: # 0.1
                return True
    return False

def get_good_info():
    while True:
        good_name = input('商品名称:').strip()
        price = input('price:').strip()
        count = input('count:').strip()
        color = input('color:').strip()
        if good_name and price and count and color:
            if not check_price(price):
                print('价格输入不合法,必须大于0')
            elif not count.isdigit() and int(count)<1:
                print('数量不合法')
            else:
                return good_name,price,count,color
        else:
            print('输入不能为空!')

def add_good():
    good_name,price,count,color = get_good_info()
    if good_name not in all_goods:
        all_goods[good_name]= {
            'price':price,
            'count':count,
            'color':color
        }
        op_file(FILE_NAME,all_goods)
        print('添加完成!')
    else:
        print('商品已经存在!')

def update_good():
    good_name,price,count,color = get_good_info()
    if good_name in all_goods:
        all_goods[good_name]= {
            'price':price,
            'count':count,
            'color':color
        }
        op_file(FILE_NAME,all_goods)
        print('修改完成!')
    else:
        print('商品不存在!')

def query_good():
    good_name = input('商品名称:').strip()
    if good_name in all_goods:
        print(all_goods.get(good_name))
    else:
        print('商品不存在')

def delete_good():
    good_name = input('商品名称:').strip()
    if good_name in all_goods:
        all_goods.pop(good_name)
        op_file(FILE_NAME,all_goods)
    else:
        print('商品不存在')

def main():
    for i in range(3):
        choice = input('请输入你的选择'
                       '1、添加'
                       '2、修改'
                       '3、删除'
                       '4、查看'
                       '5、退出')
        if choice=="1":
            add_good()
        elif choice=="2":
            update_good()
        elif choice=="3":
            delete_good()
        elif choice=="4":
            query_good()
        elif choice=="5":
            quit('程序退出')
        else:
            print('输入错误,请重新输入!')
            return main()
main()

 JSON文件:

{
    "phone": {
        "count": 10,
        "color": "red",
        "price": 100
    },
    "mac": {
        "count": "98",
        "color": "u767du8272",
        "price": "98.99"
    },
    "car": {
        "count": "98",
        "color": "black",
        "price": "9999"
    }
}
原文地址:https://www.cnblogs.com/lilyzhang-2018/p/9890763.html