【问题标题】:Python: List all the file names in a directory and its subdirectories and then print the results in a txt filePython:列出一个目录及其子目录中的所有文件名,然后将结果打印到一个txt文件中
【发布时间】:2022-05-16 20:45:34
【问题描述】:

我的问题如下。我想列出我的目录及其子目录中的所有文件名,并将该输出打印在 txt 文件中。现在这是我到目前为止的代码:

import os

for path, subdirs, files in os.walk('\Users\user\Desktop\Test_Py'):
   for filename in files:
     f = os.path.join(path, filename)
     a = open("output.txt", "w")
     a.write(str(f)) 

这会列出文件夹中文件的名称(共有 6 个),但每个新文件都会覆盖旧文件,因此在任何给定时间 output.txt 文件中只有一个文件名。如何更改此代码以便将所有文件名写入 output.txt 文件中?

【问题讨论】:

  • open 语句移到循环之外。
  • 你搜索过吗?不久前,我刚刚阅读了几乎完全相同的副本……

标签: python python-2.7


【解决方案1】:

不要在for 循环中打开文件。在for 循环之前打开它

喜欢这个

import os

a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
   for filename in files:
     f = os.path.join(path, filename)
     a.write(str(f) + os.linesep) 

或者使用上下文管理器(这是更好的做法):

import os

with open("output.txt", "w") as a:
    for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'):
       for filename in files:
         f = os.path.join(path, filename)
         a.write(str(f) + os.linesep) 

【讨论】:

  • 您应该使用with 语句打开一个文件,以便在循环结束时文件会自动关闭。
  • 最好使用with,打开的文件会在完成后关闭。即,“与 open("output.txt", "w") as a"
  • 可能还需要在某处进行换行。 :^)
  • 谢谢你帮我做的:)
【解决方案2】:

您正在以写入模式打开文件。您需要附加模式。详情请见manual

改变

a = open("output.txt", "w")

a = open("output.txt", "a")

【讨论】:

    【解决方案3】:

    您可以使用以下代码仅写入文件夹中的文件名。

    import os
    
    a = open("output.txt", "w")
    for path, subdirs, files in os.walk(r'C:\temp'):
       for filename in files:
          a.write(filename + os.linesep) 
    

    【讨论】:

      【解决方案4】:

      如果您想避免在文本文件中创建新行,请在上下文管理器中包含 newline=''。您以后不必格式化文本文件。

      写入文件夹/目录中所有文件名称的代码:

      file_path = 'path_containing_files'
      with open("Filenames.txt", mode='w', newline='') as fp:
          for file in os.listdir(file_path):
              f = os.path.join(file_path, file)
              fp.write(str(f) + os.linesep)
      

      如果您想写入特定文件类型的文件名,例如。 XML,可以添加if条件:

      file_path = 'path_containing_files'
      with open("Filenames.txt", mode='w', newline='') as fp:
          for file in os.listdir(file_path):
              if file.endswith('.xml'):
                  f = os.path.join(file_path, file)
                  fp.write(str(f) + os.linesep) 
      

      【讨论】:

        猜你喜欢
        • 2017-03-15
        • 2014-02-24
        • 1970-01-01
        • 2012-09-02
        • 2017-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多