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)