def enumerate_string(path=None, str_to_enum=None): ''' Read file from path.ext and enumerate each occurrence of str_to_enum with a counter. Write result to path-enum.ext Example: file content = AAAAxxxAAAAxxxxxAAAAxAAAA str_to_enum = AAAA result = 0AAAxxx1AAAxxxxx2AAAx3AAA ''' with open(path, 'rb') as f: content = f.read() newpath = get_newpath(oldpath=path, str_to_insert='-enum') # create a generator to find all start positions of the substring occurences = (m.start() for m in re.finditer(str_to_enum, content)) newcontent = _enumerate_string(content, occurences) with open(newpath, 'wb') as f: f.write(newcontent) return newpath
def test_get_newpath(self): oldpath = '/path/to/foo.txt' newpath = filetools.get_newpath(oldpath, 'bar') self.assertEqual('/path/to/foobar.txt', newpath)