写完再关闭文件
读写文件的三种模式的了解一下。
用with语句的话,可以自动帮你在用完之后关闭文件。不用with的话,在for 结束后关闭文件- # -*- coding: utf-8 -*-
- """
- Spyder Editor
-
- This is a temporary script file.
- """
- import os
-
- with open("list.txt","w") as f:
- for l in os.listdir("."):
- f.write(l+"\r\n")
- f.close()#假设不用with
复制代码
|