I'm creating a program to update a text file, that has a list of cities:
New York City
New York
USA
Newark
New Jersey
USA
Toronto
Ontario
Canada
If I wanted to delete the details for Newark using a bash script, I can do this:
sed -i "/Newark/,+3d" test.txt
And that would leave me with the following:
New York City
New York
USA
Toronto
Ontario
Canada
However, I would like to do this in Python, and I'm having issues figuring out how to delete the following lines, after the line with Newark. I can delete Newark:
with open('test.txt') as oldfile, open('test2.txt', 'w') as newfile:
for line in oldfile:
if not "Newark" in line:
newfile.write(line)
os.remove('test.txt')
os.rename('test2.txt', 'test.txt')
But this does nothing for the remaining two lines, and creates a new file I then have to use to replace the original file.
- How can I go about mimicing the sed command's functionality with Python?
- Is there any way to do an in file edit, so I do not have to create and replace the file everytime I need to delete from it?