Board logo

标题: [问题求助] Python如何把文件列表存入指定文件? [打印本页]

作者: netdzb    时间: 2019-7-6 22:51     标题: Python如何把文件列表存入指定文件?

for file in files:
        print file

# 上面是打印出的文件列表,虽然能够通过重定向的存入指定文件,
# 能否能用python读写的方式存入指定文件呢
作者: netdzb    时间: 2019-7-6 23:55

这样写对不对啊?

f1=open('list.txt','w')
        print file
        f1.write(file)
        f1.close()

运行后list.txt是0字节。不知道应该怎么改?
作者: codegay    时间: 2019-7-7 13:38

写完再关闭文件
读写文件的三种模式的了解一下。

用with语句的话,可以自动帮你在用完之后关闭文件。不用with的话,在for 结束后关闭文件
  1. # -*- coding: utf-8 -*-
  2. """
  3. Spyder Editor
  4. This is a temporary script file.
  5. """
  6. import os
  7. with open("list.txt","w") as f:
  8.     for l in os.listdir("."):
  9.         f.write(l+"\r\n")
  10.     f.close()#假设不用with
复制代码





欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2