其他分享
首页 > 其他分享> > 文件处理

文件处理

作者:互联网

#文件读取
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)

标签:文件,处理,lines,day1,Python,report,txt,open
来源: https://www.cnblogs.com/zhangcaiwang1/p/16304069.html