Python写入文件测试-邯郸学步第一篇

file:

1月:3000
2月:1000
3月:4000
4月:8000
5月:10000
6月:12000
7月:17000
8月:4000
9月:6000
10月:5000

1. 读模式打开文件

filename=f"D:\test.txt"
#with open("D:/test.txt",mode='r',encoding='utf-8') as f:

with open(file="notebook", mode='r', encoding='utf-8') as f:

     content=f.read() #打印文件原文

       content=f.readline() 读入第一行
      content=f.readlines() 读入多行存入列表

打印列表:
['1月:3000\n', '2月:1000\n', '3月:4000\n', '4月:8000\n', '5月:10000\n', '6月:12000\n', '7月:17000\n', '8月:4000\n', '9月:6000\n', '10月:5000']

2.  替换换行符,并逐个apend生成新列表

new_list = []
for con in content:
    newcontent = con.replace("\n","")
    new_list.append(newcontent)
new_list :
['1月:3000', '2月:1000', '3月:4000', '4月:8000', '5月:10000', '6月:12000', '7月:17000', '8月:4000', '9月:6000', '10月:5000']

3. 获取列表末尾元素并append生成money数组,可以int或float类型,用于做图

    money=newcontent.split(":")[-1]
    new_list.append(newcontent)
    money_list.append(float(money))
[3000.0, 1000.0, 4000.0, 8000.0, 10000.0, 12000.0, 17000.0, 4000.0, 6000.0, 5000.0]

4. 删除空行line.strip()
求和,求均值
count=0
for money in money_list:
    count +=money

print(sum)--内嵌函数, 均值可以累加或使用内嵌函数

print("平均值1:",count/len(new_list))
avg=sum(money_list)/len(new_list)
print("平均值2:",avg)
print(count)

5. 简单作图
import numpy as np
import matplotlib.pyplot as plt
from pylab import mpl   # 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

x = [1,2,3,4,5,6,7,8,9,10]
y = money_list
plot = plt.plot(x,y,'r')
plt.title('销售额graph')
plt.xlabel('month')
plt.ylabel('money')
plt.legend(labels=['test']) #指定label避免报错
plt.show()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值