I’m trying to use the fileinput module to iterate over a bunch of files and replace a single line in them. This is how my code looks:
def main():
for root, dirs, files in os.walk('target/generated-sources'):
for line in fileinput.input([os.path.join(root, file) for file in files if file.endsWith('.java')], inplace=True):
match = re.search(r'@Table\(name = "(.*)"\)', line)
output = "".join(['@Table(name = "', PREFIX, match.group(1)[MAX_TABLENAME_LEN - len(PREFIX)], '")', '\n']) if match else line
print output,
The problem I face is that I get no error, and the script somehow seems to block. I’m using Python 2.5.2.
Your list comprehension is returning empty lists when a root does not contain
.javafiles. When your script passes an empty list tofileinput.input(), it reverts to the default expecting input from stdin. Since there is nothing coming in from stdin, your script blocks.Try this instead:
Alternatively, split up the logic of the file discovery. The following creates a generator which produces a list of files which you can then use as an input to
fileinput.