Python文件输入输出 I/O(IO)

with语句的好处就只是在于打开一个文件最后不用手动去close了

当with语句中的代码执行完毕之后,with语句打开的文件就会自动被python关闭

否则要像这样

f = open('a,.txt', 'r')

s = f.read()

f.close()

如果后面不关闭,python就将一直占用这个文件的系统资源

读文件

with open("D://input.txt", "r") as f:
#with open("D://input.txt", "r", encoding='utf-8') as f:
    res = f.readlines()
    print(res)
f = open('input.txt','r',encoding = 'utf-8')
text = f.readlines()
print(text)
f.close()

这两种写法是一样的

只是with as的写法不用close文件了

整个文件按行读完

with open("D://mc.txt", "r") as f:
    for line in f:
        print(line)

#或者

with open("D://data12.txt", "r") as f:
    print(f.readline())

写文件

file = open("data.txt","w")
file.write("Hello world") 
file.close()

-----------------------

f = open("1.txt","w")
print(img,file=f)
f.close()

with open('input.txt','w',encoding='utf-8') as f:
    text = 'hello\nworld\n'
    f.write(text)
    f.write('yesterday')
#这样就不用close了

如果要换行就加上\n

文件清空

with open("test.txt", 'w') as f:
  f.write('')

计算绩点的程序

ans = 0.0
suma = 0
with open("D://data12.txt", "r") as f:
    for line in f:
        a, b = line.split()
        a = int(float(a))
        b = float(b)
        suma += a
        ans += a * b

ans /= suma
print(ans)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值