0

I have a relatively big repo (too big for me to do the task manually) that needs a simple refactoring at every file.

I want to iterate over all files in my repo and replace statements like:

from <old_location> import <something>
to
from <new_location> import <something>

I have written the following code

import os


def refactor_imports(rootdir=PATH):
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            process_file(os.path.join(subdir, file))


def process_file(path):
    with open(path, 'a') as f_obj:
        for line in f_obj:
            if not line.startswith("from"):
                return

            else:
                #TODO: rewrite the line

and I am not sure how to complete it, how can you rewrite the file?
Is there a way to do so without reading the entire file content in memory?

Eliran Turgeman
  • 1,526
  • 2
  • 16
  • 34
  • 1
    load the file[s] into string and use `replace` – balderman Aug 09 '21 at 12:10
  • @balderman can it be done in a different way? – Eliran Turgeman Aug 09 '21 at 12:11
  • 1
    Why you want to do it in a different way? – balderman Aug 09 '21 at 12:12
  • Perhaps you could write a new file, line by line, and then move it into the old one, replacing it. That way you avoid reading all the file at once or storing it incrementally into a variable – MatBBastos Aug 09 '21 at 12:12
  • how big are your files? can they fit into the memory individually? if so you can read them one by one and replace. if not, read the file line by line and write line by line to an another file and rename the file – kahveciderin Aug 09 '21 at 12:13
  • Though I'd guess the files aren't big enough to be a problem reading one by one into memory. You tell us, however – MatBBastos Aug 09 '21 at 12:14
  • assuming I go with reading the entire file, I should change the file mode to write and after replacing everything I need I just write it to the same file object? – Eliran Turgeman Aug 09 '21 at 12:17
  • 1
    Is that case, I believe you can refer to [this answer](https://stackoverflow.com/a/4719562/12818877). – MatBBastos Aug 09 '21 at 12:23

0 Answers0