[Solved] how to replace first line of a file using python or other tools?


Using Python 3:

import argparse

from sys import exit

from os.path import getsize

# collect command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--parameter', required=True, type=str)
parser.add_argument('-f', '--file', required=True, type=str)
args = parser.parse_args()

# check if file is empty
if getsize(args.file) == 0:
    print('Error: %s is empty' % args.file)
    exit(1)

# collect all lines first
lines = []
with open(args.file) as file:
    first_line = next(file)

    # Check if '=' sign exists in first line
    if '=' not in first_line:
        print('Error: first line is invalid')
        exit(1)

    # split first line and append new line
    root, parameter = first_line.split('=')
    lines.append('%s=%s\n' % (root, args.parameter))

    # append rest of lines normally
    for line in file:
        lines.append(line)

# rewrite new lines back to file
with open(args.file, 'w') as out:
    for line in lines:
        out.write(line)

Which works as follows:

$ cat hanlp.properties
root=/Users/pan/Documents
other content
$ python3 script.py --file hanlp.properties --parameter /Users/a/b
$ cat hanlp.properties
root=/User/a/b
other content

solved how to replace first line of a file using python or other tools?