I have this file and I would like to be able to write text n
lines before the end of the file in python, I know the write method exists however it only inserts text at the very end of the file. I would like to do something like this:
INSERT INTO `mod238_yoast_seo_meta` VALUES("12749", "0", "0");
INSERT INTO `mod238_yoast_seo_meta` VALUES("12755", "0", "0");
INSERT INTO `mod238_yoast_seo_meta` VALUES("12757", "1", "0");
INSERT INTO `mod238_yoast_seo_meta` VALUES("12765", "1", "0");
INSERT INTO `mod238_yoast_seo_meta` VALUES("12774", "1", "0");
INSERT INTO `mod238_yoast_seo_meta` VALUES("12785", "1", "0");
/* I would like to be able to insert some text here with python/*
SET FOREIGN_KEY_CHECKS = 1;
/* Duplicator WordPress Timestamp: 2021-01-08 15:49:50*/
/* DUPLICATOR_MYSQLDUMP_EOF */
/* DUPLICATOR_MYSQLDUMP_EOF */
being the very last line of the file, thanks very much in advance! Also I use python 3.8.
One way you could approach this problem is to read the file into a list of lines. Insert your new line into which ever position you want. Then write that list of lines out to a new file.
If you know the line number to insert you could use that position directly. If you need to calculate the line position based on number of lines from bottom of file, you can calculate the line position as the difference between the total number of lines and your number N.
That could look something like this:
# Insert text n lines before the end of file
file_path = 'text.txt'
line_to_insert = '/*this is my inserted line*/\n'
lines_from_bottom = 4
with open(file_path) as file:
lines = file.readlines()
insert_position = len(lines) - lines_from_bottom
lines.insert(insert_position, line_to_insert)
with open('new_file.txt', 'w') as new_file:
for line in lines:
new_file.write(line)