Tuesday, January 28, 2020

Python - function to write data into an existing python file

The code below is trying to add a file path to the beginning of an existing .py file.


def write_path(file_path):
    with open(file_path, 'r') as f:
        data = f.read()
    with open(file_path, 'w') as g:
        if data.splitlines()[0] != str_path:
            g.write(str_path + '\n' + data)
        else:
            g.write(data)

No comments:

Post a Comment