2023-03-08 08:51:04
open函数中的文件名默认是寻找当前目录下的这个文件
如果当前目录下没有就会报错。建议在日常使用中写上绝对路径(完整路径)
1 2 3 4 5 |
当前目录下没有a.txt 下面是报错

我的D盘下有a.txt这个文件,并且写了绝对路径
1 2 3 4 5 |

with open() as f就相当于 f = open()
第一种方式会在程序结束后自动回收内存。可以不用写f.close()。其余用法一样
# -*- encoding:utf-8 -*-with open('a.txt') as f: res = f.readline() print(res)# -*- encoding:utf-8 -*-with open('D:\\a.txt') as f: res = f.readline() print(res)
2021-12-07 11:54:19