我整理了这个脚本来帮助我在特定文件中执行搜索。它做的事情类似于 grep,但我需要比 grep 提供的更具体的东西,所以我正在尝试使用 Python。
我有一堂课,它有三种方法。第二种方法listOccurrencesOfToDoInFile
(第 30 行)失败。这是一个小脚本,但由于制表符在 Python 中很重要,因此我将其概括为一个要点,在这里. 谁能告诉我为什么我看似有效的 Python 无效?
import os
import keyword
import sys
class Toodles:
def walkAndList(directory):
for dirname, dirnames, filenames in os.walk(directory):
# print path to all filenames.
for filename in filenames:
workingFilename = os.path.join(dirname, filename)
if(isSourceFile(filename)):
listOccurrencesOfToDoInFile(filename)
# Advanced usage:
# editing the 'dirnames' list will stop os.walk() from recursing into there.
if '.git' in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
for dirs in dirnames:
self.walkAndList(os.path.join(dirname, dirs)
# Find occurences of "todo" and "fixme" in a file
# If we find such an occurence, print the filename,
# the line number, and the line itself.
def listOccurrencesOfToDoInFile(aFileName):
input = open(aFileName)
currentLine = 1
for (line in input):
line = line.lower()
currentLine = currentLine + 1
needle = "todo"
if (needle in line):
sys.stdout.write(aFileName + " (" + str(currentLine) + ")" + line)
#Todo: add a comment
def isSourceFile(self, name):
fileName, fileExtension = os.path.splitext(name)
if (".m" in fileExtension or ".c" in fileExtension or ".h" in fileExtension):
return True
return False
if ( __name__ == "__main__") {
a = Toodles()
a.walkAndList('.')
}