ArekBulski ArekBulski - 2 months ago 6
Python Question

Removing six.b from multiple files

I have dozens of files in the project and I want to change all occurences of

six.b("...")
to
b"..."
. Can I do that with some sort of regex bash script?

Answer

It's possible entirely in Python, But I would first make a backup of my project tree, and then:


import re
import os

indir = 'files'

for root, dirs, files in os.walk(indir):
    for f in files:
        fname = os.path.join(root, f)
        with open(fname) as f:
            txt = f.read()
        txt = re.sub(r'six\.(b\("[^"]*"\))', r'\1', txt)
        with open(fname, 'w') as f:
            f.write(txt)
        print(fname)