Created
July 18, 2020 10:09
-
-
Save messa/07941f2bdbec7a488c731ecd99a64628 to your computer and use it in GitHub Desktop.
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
#!/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