0

I have to add from constants import MY_CONSTANT to 100 python files.

Is there a simple and efficient way to do it?

  • 1
    Write a Python script to loop the files and add the line :) – Tomerikoo Feb 25 '20 at 16:22
  • You can regex replace those files: `(^)` with `$1from constants import MY_CONSTANT` but why? – Sayse Feb 25 '20 at 16:22
  • 6
    This is a terrifying question. Why do you even have one hundred files that need to share a constant with a generic name? This should be a warning sign that you have left the path of righteousness. – markemus Feb 25 '20 at 16:23
  • Does this answer your question? [Prepend line to beginning of a file](https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file) – Tomerikoo Feb 25 '20 at 16:27
  • 1
    How do you plan to either 1) Remove the *current* definition of `MY_CONSTANT` or 2) start to *use* `MY_CONSTANT` in each file? You may as well add the line by hand while addressing this issue. – chepner Feb 25 '20 at 16:29
  • 1
    `for f in *.py; do new=${f}_new ; echo 'import foo from bar' > $FILENAME; less $f >> $FILENAME; done` – Bart Barnard Feb 25 '20 at 16:35

1 Answers1

3

You can just treat python files like any other text files and write to them. Assuming they are all in the same folder (if not just adapt the loop to go through the relevant folders):

for file in os.listdir(folderpath):   
    if file.endswith('.py'):
        with open(file,'r+') as f:
            content = f.read()
            f.seek(0, 0)
            f.write('from constants import MY_CONSTANT' + '\n' + content)  
KJTHoward
  • 806
  • 4
  • 16
  • 2
    One problem with this: either the files already have a definition of `MY_CONSTANT` in place that will override the imported value, or the files aren't currently using `MY_CONSTANT`. Either way, additional editing will be needed, in which case there's little point in automating this part of the task. – chepner Feb 25 '20 at 16:28
  • 3
    @chepner That is true, but that's a problem with the question, not my answer. The question was just to add this line to multiple files, which my answer does. – KJTHoward Feb 25 '20 at 16:30