Python如何把文件列表存入指定文件?
for file in files:print file
# 上面是打印出的文件列表,虽然能够通过重定向的存入指定文件,
# 能否能用python读写的方式存入指定文件呢 这样写对不对啊?
f1=open('list.txt','w')
print file
f1.write(file)
f1.close()
运行后list.txt是0字节。不知道应该怎么改? 写完再关闭文件
读写文件的三种模式的了解一下。
用with语句的话,可以自动帮你在用完之后关闭文件。不用with的话,在for 结束后关闭文件[code]# -*- 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
[/code]
页:
[1]