Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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