【问题标题】:Write the output of os.walk into *.txt file [duplicate]将 os.walk 的输出写入 *.txt 文件 [重复]
【发布时间】:2020-09-11 15:35:13
【问题描述】:

我是 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()

工作正常并打印文件。

现在使用文件():

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

dirlist()

我希望你能帮助我。 谢谢。

【问题讨论】:

  • 您正在打开文件进行写入,因此每次都将其截断。您需要在循环之前使用with 语句打开它一次

标签: python-3.x os.walk


【解决方案1】:

在您的情况下,您正在为每个条目覆盖文件。尝试 以下:

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()

【讨论】:

    【解决方案2】:

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

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

    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()
    

    【讨论】:

      【解决方案3】:
      def dir_list():
      for root, dirs, files in os.walk(".", topdown=False):
          for name in dirs:
              file = open("files.txt", "a+")
              print(name + "\n",file=file)
              file.close()
      
      dirlist()
      

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

      【讨论】:

        猜你喜欢
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-21
        • 2017-04-29
        相关资源
        最近更新 更多