Unfortunately, I think you have to open the file, read it, delete the lines, rewrite the file. So I'd do something like this:
def delete_lines(file, delete_lines=[]):
with open(file, "r") as f:
lines = f.readlines()
for line in delete_lines:
if line < len(lines):
lines[line] = ""
with open(file, "w") as f:
f.writelines(lines)
delete_lines(r"/my_path/to/file", delete_lines=[0, 5, 7])
Not that there is any significant difference, but alternatively, you can join the lines together and write it as a string:
def delete_lines(file, delete_lines=[]):
with open(file, "r") as f:
lines = f.readlines()
for line in delete_lines:
if line < len(lines):
lines[line] = ""
with open(file, "w") as f:
f.write("".join(lines))
delete_lines(r"/my_path/to/file", delete_lines=[0, 5, 7])
Here is some sample data:
abc
def
ghi
jkl
mno
pqr
stu
vwx
yz1
234
567
890
098
765
543
21z
yxw
etc
etc
etc
and its output to the file
def
ghi
jkl
mno
stu
yz1
234
567
890
098
765
543
21z
yxw
etc
etc
etc
EDIT to meet the criteria for the OP:
def delete_lines(file, max_history=15):
with open(file, "r") as f:
lines = f.readlines()
if len(lines) > max_history:
del lines[max_history + 1:]
del lines[0]
with open(file, "w") as f:
f.writelines(lines)
delete_lines(r"/my_path/to/file")