Last active
July 22, 2020 16:45
-
-
Save hdf/a975bb038f707cbdc20a4da75976c751 to your computer and use it in GitHub Desktop.
Replace a marked block part of a file, with the contents of another file. Ex.: replace.py file.html data.txt //begin //end
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
orig = sys.argv[1] if len(sys.argv) > 1 else 'kocka.html' | |
data = sys.argv[2] if len(sys.argv) > 2 else 'L5_A-17_365000napig_bennmarado_3650napig.txt' | |
start = sys.argv[3] if len(sys.argv) > 3 else '// begin_data' | |
end = sys.argv[4] if len(sys.argv) > 4 else '// end_data' | |
no_backup = True if len(sys.argv) > 5 and sys.argv[5] == 'no_backup' else False | |
clean = True if data == 'clean' else False | |
with open(orig, 'r+', encoding='utf-8') as f: | |
content = f.read() | |
s = content.find(start) | |
e = content.rfind(end) | |
if s != content.rfind(start) or e != content.find(end): | |
print("More than one match for replacement block! Exiting.") | |
exit() | |
if s == content.find(start + '\n'): | |
start += '\n' | |
if e - len('\n') == content.rfind('\n' + end): | |
end = '\n' + end | |
e -= len('\n') | |
#to_replace = content[s + len(start):e] | |
if not no_backup: | |
with open(orig + '.bak', 'w', encoding='utf-8') as f2: | |
f2.write(content) | |
f.seek(0) | |
f.write(content[0:s + len(start)]) | |
if not clean: | |
with open(data, 'r', encoding='utf-8') as f2: | |
for l in f2: | |
f.write(l) | |
#f.write(content.replace(to_replace, f2.read())) # MemoryError if data file too large | |
f.write(content[e:]) | |
f.truncate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment