将os.walk的输出写入* .txt文件

问题描述

我绝对是python的初学者。我想将每个文件写入files.txt文件中的文件夹(PythonScript所在的文件夹)中。当我仅使用for循环运行脚本时,一切正常,并且可以看到文件夹的每个文件。当我插入file()函数以将其写入文件时,我只会得到文本文件中的最后一个文件夹。 mz问题在哪里?

def dir_list():
for root,dirs,files in os.walk(".",topdown=False):
    for name in dirs:
        print(name)
dir_list()

工作正常并打印文件

现在使用file():

def dir_list():
for root,topdown=False):
    for name in dirs:
        file = open("files.txt","w")
        file.write(name + "\n")
        file.close()

dirlist()

希望您能帮助我。 谢谢。

解决方法

根据您的情况,您将覆盖每个条目的文件。尝试 以下:

def dir_list():
    with open("files.txt","a") as fp:
        for root,dirs,files in os.walk(".",topdown=False):
            for name in dirs:
                fp.write(name + "\n")

dirlist()
,

之所以发生这种情况,是因为每次循环时都要重新打开文件,并且由于是以写模式打开文件(通过将“ w”作为打开函数的参数传递),因此文件的先前内容会被获取。覆盖,最后只保存最后一次迭代中写入的内容。

要解决此问题,您应该在进入循环之前仅打开文件一次:

def dir_list():
   with open("files.txt","a") as fp:
      for root,topdown=False):
         for name in dirs:
           fp.write(name + "\n")

dirlist()
,
def dir_list():
for root,topdown=False):
    for name in dirs:
        file = open("files.txt","a+")
        print(name + "\n",file=file)
        file.close()

dirlist()

希望这将起作用,这是打印for循环的所有输出的非常简单的方法。
在这里,“ a +”表示您要附加输出 知道我在您的python环境中是否有效