2016-10-04 147 views
2

我已经写了一个脚本来从docx文件中删除给定的单词,并且在我的最后一个检查子文件夹项目的障碍。有人能帮我弄清楚我在执行中失败的地方吗?它适用于同一目录中的所有文件,但它现在也不会检查子文件夹项目。谢谢你的帮助。遍历子文件夹文件?

#!/usr/bin/env python3 

# Search and Replace all docx 

import os, docx 

from docx import Document 


findText = input("Type text to replace: ")        

#replaceText = input('What text would you like to replace it with: ')  


for dirs, folders, files in os.walk('.'): 
    for subDirs in dirs: 
     print('The Sub is ' + subDirs) 
     for fileNames in files: 
      print(subDirs + fileNames) 
      if fileNames.endswith('.docx'): 
       newDirName = os.path.abspath(subDirs) 
       fileLocation = subDirs + '\\' + fileNames 
       document = docx.Document(fileLocation) 
       print('Document is:' + fileLocation) 

       tables = document.tables 
       for table in tables: 
        for row in table.rows: 
         for cell in row.cells: 
          for paragraph in cell.paragraphs: 
           if findText in paragraph.text:        
            inline = paragraph.runs         
            for i in range(len(inline)): 
             if findText in inline[i].text: 
              text = inline[i].text.replace(findText, '') 
              inline[i].text = text 

       for paragraph in document.paragraphs:       
        if findText in paragraph.text:        
         inline = paragraph.runs         
         for i in range(len(inline)): 
          if findText in inline[i].text: 
           text = inline[i].text.replace(findText, '') 
           inline[i].text = text 

       document.save(fileLocation) 
+0

你说_it不会也检查子文件夹items_ - 这是否意味着实际的docx处理是不相关的。你能把这个样本修剪成一些仍然失败但不会让我们眼睛疲劳的东西吗?! – tdelaney

+1

'os.walk'走树,所以你可能不需要为子目录中的子目录:'它只是对子目录进行第二次浏览。 – tdelaney

+0

'dirs'将是一个字符串,即当前目录,因此当您为'dirs'中的子目录执行时,您正在迭代字符串中的单个字符。 –

回答

3

os.walk遍历子目录产生一个3元组对(dirpath, dirnames, filenames)每个子目录访问。当你这样做:

for dirs, folders, files in os.walk('.'): 
    for subDirs in dirs: 

事情变得非常错误。 dirs是每个迭代中子目录的名称,这意味着for subDirs in dirs:实际上是枚举目录名称中的字符。恰巧你迭代的第一个目录是".",并且运气好的话它只有一个字符目录名,这样你的for循环似乎就可以工作。

只要你走进另一个子目录(可以称其为“富”),你的代码将尝试找到子目录称为foo\ffoo\ofoo\o第二次。这是行不通的。

但你不应该自己重新枚举子目录。 os.walk已经做到了。把你的代码放到枚举部分,这会找到子树中的所有.docx

#!/usr/bin/env python3 

import os 

for dirpath, dirnames, filenames in os.walk('.'): 
    docx_files = [fn for fn in filenames if fn.endswith('.docx')] 
    for docx_file in docx_files: 
     filename = os.path.join(dirpath, docx_file) 
     print(filename) 
+0

嘿tdelany,这是一个了不起的解释,它完美的工作。对眼睛紧张的道歉。你的解决方案是如此优雅的方法。如果你不介意你能否打破基准名行。看起来好像你有多行代码,并且一次完成。再次感谢你的帮助。 – TragicWhale

+0

我扩大了操作并使用了明智的名字。 – tdelaney

+0

不知道那是什么,但至少我知道该看什么......哈。再次,非常感谢。这是为了工作,所以它会为我节省很多时间。 – TragicWhale