Name not Found
Name not Found

Reputation: 79

Python: Replace line clearing everything after line

The following is my replace line function:

def replace_line(file_name, num, replaced):
    f = open(file_name, 'r', encoding='utf-8')
    lines = f.readlines()
    lines[num] = replaced
    f.close()
    f = open(file_name, 'w', encoding='utf-8')
    f.writelines(lines)
    f.close()

I am using this following line to run my code:

replace_line('Store.txt', int(line), new)

When I run my code, it replaces that line however it also removes everything after that line. For example, if this was my list:

Upvotes: 1

Views: 219

Answers (1)

casraf
casraf

Reputation: 21694

To be honest, I'm not sure what was wrong with the original function. But I tried redoing it and this seems to work fine:

def replace_line(file_name, line_num, text):
    with open(filename, 'r+') as f:
        lines = f.read().splitlines()
        lines[line_num] = text
        f.seek(0)
        f.writelines(lines)
        f.truncate()

Please note that this overwrites the entire file. If you need to handle large files or are concerned with memory usage, you might want to try another approach.

Upvotes: 1

Related Questions