文件处理

#文件读取
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)
 
posted @ 2022-05-24 02:13  人生信条~~  阅读(32)  评论(0编辑  收藏  举报