zoukankan      html  css  js  c++  java
  • 函数

    import json
    with open('a.txt') as f: #打开文件
        res=json.load(f) #将文件内容转成字典
    
    with open('b.txt') as f: #打开文件
        res=json.load(f) #将文件内容转成字典
    
    with open('c.txt') as f: #打开文件
        res=json.load(f) #将文件内容转成字典

    为了实现以下这上功能,可以使用封装内容,提高代码复用率的办法——函数:

    def my(): #定义一个函数,def为关键字,my()为函数名
        print('函数')
    #函数必须得调用才会执行
    my()#函数名加上小括号才是调用函数
    print(my)#不会打印出东西,因为没加小括号
    def get_file_content(file_name):  #形参根据需要来决定是否要写,如果写了形参,调用时就要写实参
        with open('file_name',encoding='utf-8') as f:
            res=json.load(f)
    
    get_file_content('stus.json')#实参
    print(res)#不会打印出res,因为res是局部变量,作用域在函数里,只能在函数内部使用
    #定义一个函数:内容写入文件
    def write_file(filename,content):
        with open(filename,'w',encoding='utf-8') as f:
            json.dump(content,f,ensure_ascii=False,indent=4)        
            #f.write(json.dumps(content))
    
    #写上文件名、文件里要写的内容
    d={'name':'abc','sex':'girl'}
    #然后调用函数
    write_file('file.json',d)
    #不需要return,因为只需要执行即可
    #定义一个函数:从文件读内容
    def get_file_content(file_name):  
        #入参:传入一个文件名
        #返回值:文件内容转成字典,返回
        with open('file_name',encoding='utf-8') as f:
            res=json.load(f)
            return res
    
    #一个函数只做一件事,避免不好拆分,无法调用
    abc=get_file_content('stus.json')
    print(abc)
    每天进步一点点,快乐生活多一点。
  • 相关阅读:
    learnyou 相关网站
    hdu 3038 How Many Answers Are Wrong
    hdu 3047 Zjnu Stadium 并查集高级应用
    poj 1703 Find them, Catch them
    poj 1182 食物链 (带关系的并查集)
    hdu 1233 还是畅通工程
    hdu 1325 Is It A Tree?
    hdu 1856 More is better
    hdu 1272 小希的迷宫
    POJ – 2524 Ubiquitous Religions
  • 原文地址:https://www.cnblogs.com/yiruliu/p/9588276.html
Copyright © 2011-2022 走看看