【问题标题】:write filenames of different extention into different text files将不同扩展名的文件名写入不同的文本文件
【发布时间】:2019-03-16 12:10:29
【问题描述】:
import os

exts = ['ppt', 'pptx', 'doc', 'docx', 'txt', 'pdf', 'epub']
files = []

for root, dirnames, filenames in os.walk('.'):
    for i in exts:
        for file in filenames:
            if file.endswith(i):
                file1 = os.path.join(root, file)
                print(file1)
                with open(os.getcwd()+ r"\ally_"+i+".txt", 'w+') as f:
                    f.write("%s\n" % file1)

我正在尝试这段代码。如何使用 ex 写入系统中的所有文件。 doc 扩展为我桌面中名为 all_docs.txt 的文件? for 循环中的 file.write() 仅将每个扩展名的最后一行写入文件。

【问题讨论】:

  • 请重新格式化您的代码
  • 究竟是什么不起作用?有什么问题吗?
  • ally_doc.txt 文件中的输出仅包含 1 个文件名。但我希望我系统中的.doc 扩展名的所有文件都写入 ally_doc.txt。我应该如何解决这个问题?
  • 我认为您需要以“a”(附加)模式打开文件
  • 是的。 “a”模式有效!!非常感谢:)

标签: python file-handling os.walk


【解决方案1】:

您需要以附加模式 (a) 而不是以写入模式 (w) 打开日志文件,因为使用w,文件在写入任何新内容之前会被截断(删除所有内容) .

您可以查看open() 的文档。 This answer 还提供了所有文件模式的概览。

a 对你有用吗?

【讨论】:

    【解决方案2】:
    with open(os.getcwd()+ r"\ally_"+i+".txt", 'w+') as f:
        f.write("%s\n" % file1)
    

    根据https://docs.python.org/2/library/functions.html#open,“w+”操作会截断文件。

    模式'r+'、'w+'和'a+'打开文件进行更新(读写); 请注意,“w+”会截断文件

    【讨论】:

      【解决方案3】:

      open 的模式w+ 导致文件被截断,这是丢失行的原因,只有最后一个会保留在那里。 另一个小问题可能是这种连接路径和文件名的方法不可移植。为此,您应该使用 os.path.join

                  with open(os.path.join(os.getcwd(),"ally_"+i+".txt"), 'a') as f:
                      f.write("%s\n" % file1)
      

      另一个问题可能是在有许多目录和文件的情况下您可以拥有的周性能。 在您的代码中,您遍历目录中每个扩展名的文件名,并一次又一次地打开输出文件。 另一个问题可能是检查扩展名。在大多数情况下,扩展名可以通过检查文件名的结尾来确定,但有时它可能会产生误导。例如。 '.doc' 是一个扩展名,但在文件名 'Medoc' 中,结尾 'doc' 只是名称中的 3 个字母。 所以我针对这些问题给出一个示例解决方案:

      import os
      
      exts = ['ppt', 'pptx', 'doc', 'docx', 'txt', 'pdf', 'epub']
      files = []
      outfiles = {}
      for root, dirnames, filenames in os.walk('.'):
              for filename in filenames:
                  _, ext = os.path.splitext(filename)
                  ext = ext[1:] # we do not need "."
                  if ext in exts:
                      file1 = os.path.join(root, filename)
                      #print(i,file1)
                      if ext not in outfiles:
                          outfiles[ext] = open(os.path.join(os.getcwd(),"ally_"+ext+".txt"), 'a')
                      outfiles[ext].write("%s\n" % file1)
      for ext,file in outfiles.iteritems():
          file.close()
      

      【讨论】:

      • 对!你会如何处理这个问题?会有帮助的
      • 当然。我已经编辑了答案以包含我的建议。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多