Skip to content

Instantly share code, notes, and snippets.

@LLyaudet
Last active July 27, 2023 16:11
Show Gist options
  • Save LLyaudet/874f2530cec5ec35b5726c0554ef151c to your computer and use it in GitHub Desktop.
Save LLyaudet/874f2530cec5ec35b5726c0554ef151c to your computer and use it in GitHub Desktop.
Prepend and append to your source files
import os
for root, dirs, files in os.walk("."):
for file in files:
if file.endswith(".py"):
my_path = os.path.join(root, file)
# sed does not work on truly empty file
os.system("sed -i '1s;^;import os\\nos.system(\"echo DEBUT \" + os.path.abspath(__file__) + \" >> /tmp/montest\")\\n;' " + my_path)
os.system("echo '\\nos.system(\"echo FIN \" + os.path.abspath(__file__) + \" >> /tmp/montest\")' >> " + my_path)
# A variant to avoid complicated escaping
in . add two files:
to_prepend.supertxt
-------------------
import os
os.system("echo DEBUT " + os.path.abspath(__file__) + " >> /tmp/montest")
-------------------
to_append.supertxt mind the leading newline :)
------------------
os.system("echo FIN " + os.path.abspath(__file__) + " >> /tmp/montest")
------------------
import os
for root, dirs, files in os.walk("."):
for file in files:
if file.endswith(".py"):
my_path = os.path.join(root, file)
os.system("cat ./to_prepend.supertxt " + my_path + " > tmp.supertxt && mv tmp.supertxt " + my_path)
os.system("cat ./to_append.supertxt >> " + my_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment