Skip to content

Instantly share code, notes, and snippets.

@roman-karpovich
Last active May 14, 2019 13:44
Show Gist options
  • Save roman-karpovich/c52d169b8e97c8b544cb9a4263396934 to your computer and use it in GitHub Desktop.
Save roman-karpovich/c52d169b8e97c8b544cb9a4263396934 to your computer and use it in GitHub Desktop.
from __future__ import absolute_import, division, unicode_literals
import os
def get_py_files():
for path, folders, files in os.walk('./'):
for filename in files:
if filename.endswith('.py'):
yield path + '/' + filename
def process_file(filename):
with open(filename, 'r') as py_file:
lines = py_file.readlines()
if not lines:
return
start_index = 0
while True:
if lines[start_index].startswith('#'):
start_index += 1
else:
break
# clean empty lines at the top of the file and existing future imports as it's much simpler than modify existing :)
while True:
line = lines[start_index]
if line == '\n' or '__future__' in line:
del lines[start_index]
else:
break
lines.insert(start_index, 'from __future__ import absolute_import, division, unicode_literals\n')
lines.insert(start_index + 1, '\n')
with open(filename, 'w') as py_file:
py_file.writelines(lines)
if __name__ == '__main__':
for py_file_name in get_py_files():
process_file(py_file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment