Skip to content

Commit c81e0b9

Browse files
author
Jonathan Rocher
committed
Adding a utility to prepend text to a file.
1 parent 5a22c07 commit c81e0b9

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

recursive_prepend.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
""" Walk through a source tree and prepend some text at the top.
2+
"""
3+
import os
4+
from os.path import join
5+
6+
txt2prepend = '''
7+
""" This is a copy of the same module from VMA version 1.*. It is brought into
8+
VMA 2.* to be able to support reading the old file format.
9+
"""
10+
# importing the old vma as the vma alias so that we don't have to change any of
11+
# the code below.
12+
import vma.OLD_vma as vma
13+
'''
14+
15+
def prepend_content(filename):
16+
""" Update one file by adding the text above to its beginning
17+
"""
18+
f = open(filename, "r")
19+
content = f.read()
20+
f.close()
21+
try:
22+
f2 = open(filename, "w")
23+
f2.write(txt2prepend + "\n")
24+
f2.write(content)
25+
f2.close()
26+
except Exception as e:
27+
print "Something went wrong: %s" % e
28+
import IPython ; IPython.embed()
29+
30+
def apply_prepend_to_dir(dirname, ext_list = [".py"],
31+
elems2ignore = ["__init__.py"]):
32+
""" Recursively applying a prepending opertion to all files below
33+
"""
34+
for filename in os.listdir(dirname):
35+
if filename in elems2ignore:
36+
continue
37+
filename = join(dirname, filename)
38+
is_eligible_file = (os.path.isfile(filename) and
39+
os.path.splitext(filename)[1] in ext_list)
40+
if is_eligible_file:
41+
prepend_content(filename)
42+
elif os.path.isdir(filename):
43+
apply_prepend_to_dir(filename)
44+
else:
45+
print "Skipping %s" % filename
46+
return

0 commit comments

Comments
 (0)