• 文件处理


    #文件读取
    path=r'D:\Python学习\day1\a.txt'
    f=open(path,encoding='utf-8')
    print(f)
    txt=f.read()
    print(txt)
    f.close()

    #文件写入
    # path=r'D:\Python学习\day1\a.txt'
    # f=open(path,'w')
    # f.write('this is test')
    # f.closed

    #统计文件里面函数次数
    #s='def func():'
    #s.startswith('def') and s.endswith(':')
    fname=r'D:\Python学习\day1\练习.py'
    f=open(fname,encoding='utf8')
    func_nums=0
    for line in f:
    line = line.strip() #去掉\n
    if line.startswith('def') and line.endswith('):'):
    # print(line)
    func_nums+=1
    print(func_nums)

    #产生数学成绩单
    import random
    def genReport(path,total):
    start=1
    report= [ '%d name_%d %d \n' %(i,i,random.randint(30,100)) for i in range(1,total+1)]
    f = open(path,'w')
    f.writelines(report)
    f.close()
    def megreReport(ch_report,math_report,myfile):
    math_lines = open(math_report).readlines()
    ch_lines= open(ch_report).readlines()
    r = [s.strip().split()[-1] for s in ch_lines]
    megre_lines= [f'{s1.strip()}{s2} \n' for s1,s2 in zip(math_lines,r)]
    print(megre_lines)
    f=open(myfile,'w')
    f.writelines(megre_lines)
    f.close()

    if __name__== '__main__':
    mathfile=r'D:\Python学习\day1\math_report.txt'
    chfile=r'D:\Python学习\day1\ch_report.txt'
    mfile=r'D:\Python学习\day1\merge_report.txt'
    genReport(mathfile,5)
    genReport(chfile, 5)
    megreReport(chfile,mathfile,mfile)





    #最高分
    fpath=r'D:\Python学习\day1\merge_report.txt'
    f=open(fpath)
    lines=f.readlines()
    # print(lines)
    # linedata= lines[0].strip().split() #打印lines 里面第一个元素
    # print(linedata)
    rows=[i.strip().split() for i in lines] #遍历输出所有元素
    print(rows)
    keys=['sid','name','math','chinese']
    reports=([dict(zip(keys,row)) for row in rows])
    print(reports)
    print(max([ i.get('math',0) for i in reports])) #数学最大成绩
    print(max([b.get('chinese',1)for b in reports])) #语文最大成绩
    
    
    #使用namedtuple获取字典中的元素的值
    from collections import namedtuple
    Report=namedtuple('Report',keys)
    r1=Report(**dict(zip(keys,rows)))
    print(r1.chinese)
     
  • 相关阅读:
    话说地址栏的URL的最大长度
    程序员,我拿什么来拯救自己
    把女友升级为老婆的时候发生的BUG
    一个精典asp程序引发的错误引起的思考
    [转]提高 Web Service 数据传输效率的基本方法
    整理发布html的select控件实用js操作
    asp.net简单实现导出excel报表
    c#简单实现生成csv文件
    利用sql server直接创建日历
    jQuery学习笔记:效果
  • 原文地址:https://www.cnblogs.com/zhangcaiwang1/p/16304069.html
Copyright © 2020-2023  润新知