Name not Found Name not Found - 23 days ago 5
Python Question

Python: Replace line clearing everything after line

The following is my replace line function:

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


I am using this following line to run my code:

replace_line('Products.txt', int(line), tenminus_str)


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

12345670
Product1
3
44444440
Product2
1


And [i] was 3. It would replace 3 with whatever number I wanted. Let's say 10 and remove everything below it and the line above Product1.

Product1
10


How would I fix this? Thanks.

Answer

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()