史**_python保存为txt

这是帮史**做的一个小作业,算是锻炼了一下Python如何保存为txt文档吧

import pandas as pd
import datetime
test=pd.read_excel('9c70d34d12b9b07fad58192eaa38a5c7.xlsx')
test.head()
now_time = datetime.datetime.now()
X=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
filename = 'test.txt'
with open(filename,'w') as f: # 如果filename不存在会自动创建, 'w'表示写数据,写之前会清空文件中的原有数据!
    a=("学号:10,姓名:黄婷婷,时间{0}").format(X)
    f.write(a)
    f.write("\n--------------------------")
with open(filename,'a') as f: # 'a'表示append,即在原来文件内容后继续写数据(不清楚原有数据)
    b=('英语平均分: {0}').format(int(test['英语'].mean()))
    f.write("\n")
    f.write(b)
    b=('数学平均分: {0}').format(int(test['数学'].mean()))
    f.write("\n")
    f.write(b)
    a=('计算机平均分: {0}').format(int(test['计算机'].mean()))
    f.write("\n")
    f.write(a)
    a=('英语最高分: {0},最低分 {1}').format(test['英语'].max(),test['英语'].min())
    f.write("\n")
    f.write(a)
    a=('数学最高分: {0},最低分 {1}').format(test['数学'].max(),test['数学'].min())
    f.write("\n")
    f.write(a)
    a=('计算机最高分: {0},最低分 {1}').format(test['计算机'].max(),test['计算机'].min())
    f.write("\n")
    f.write(a)
    f.write("\n--------------------------\n")
test1=test.loc[(test['英语']>test['英语'].mean())&(test['数学']>test['数学'].mean())&(test['计算机']>test['计算机'].mean())]
with open(filename,'a') as f: # 'a'表示append,即在原来文件内容后继续写数据(不清楚原有数据)
    f.write('三门课的成绩均高于各自课程平均分的学生')
    for i in test1.index:
        b=('{},{},(英语:{},数学:{},计算机:{})').format(test1['学号'][i],test1['姓名'][i],test1['英语'][i],test1['数学'][i],test1['计算机'][i])
        f.write("\n")
        f.write(b)
    f.write("\n--------------------------\n")

test['总分']=test['英语']+test['数学']+test['计算机']
test=test.sort_values(by='总分',ascending=False)
with open(filename,'a') as f: # 'a'表示append,即在原来文件内容后继续写数据(不清楚原有数据)
    a=('总分最高的学生为:{0},{1},总分:{2}').format(test['学号'][test.index[0]],test['姓名'][test.index[0]],test['总分'][test.index[0]])
    f.write(a)
发布了76 篇原创文章 · 获赞 23 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39309652/article/details/103744970