Skip to content

Instantly share code, notes, and snippets.

@messa
Created July 18, 2020 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save messa/07941f2bdbec7a488c731ecd99a64628 to your computer and use it in GitHub Desktop.
Save messa/07941f2bdbec7a488c731ecd99a64628 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from argparse import ArgumentParser
from pathlib import Path
def replace_line(path, line_number, text):
if isinstance(text, str):
text = text.encode()
assert isinstance(text, bytes)
path = Path(path)
temp_path = path.with_name(path.name + '.tmp')
try:
with path.open(mode='rb') as f1:
with temp_path.open(mode='wb') as f2:
for n, line in enumerate(f1, start=1):
if n == line_number:
f2.write(text)
f2.write(b'\n')
else:
f2.write(line)
temp_path.rename(path)
finally:
# pokud se neco nepovedlo, smazeme temp soubor
if temp_path.exists():
temp_path.unlink()
def main():
p = ArgumentParser()
p.add_argument('file')
p.add_argument('line', type=int)
p.add_argument('text')
args = p.parse_args()
replace_line(args.file, args.line, args.text)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment