read file in s3 using python

Last updated on August 29th, 2022 at 01:53 pm

In this tutorial we are going to delete a specific line in a file that starts with a string.

Let us first create a simple text file ‘myfile‘, Content of the file is as follows.

python-text-file-processing
This is the first line
Second line
The third line
I love Python
I love PHP
Text file processing

The python script we are going to create will delete a specific line starting with the word defined. The line to be deleted is assigned to the variable “str“. Save the code as “delete.py

#!/usr/bin/python
def deleteLine():
 fn = 'myfile'
 f = open(fn)
 output = []
 str="The"
 for line in f:
   if not line.startswith(str):
    output.append(line)
 f.close()
 f = open(fn, 'w')
 f.writelines(output)
 f.close()
deleteLine()

In this script we are going to delete third line which starts with “The“, Hence we define ‘str=”The”‘. You can change this value to any of your choice according to your requirement.

How function deleteLine() works?

1)Inside this function we are defining the file name “myfile”
2)Open the file
3)Assign an array named output.
4)Assign ‘str’ to line which needs to be deleted.
5)Then reading each line and appending all lines to output array which doesn’t start with line “The”
6)We are closing the file using f.close()
7)Next step is to open the file again and write data which is saved to “output” array to the same file.
8)Note that in this specific example we are opening the file reading each line and then saving in to output array. Then open same file again and write data to it. Last step is to call this function deleteLine()

Output: As you can see below after running the python script line starting with “The” got deleted.

$ cat myfile
This is the first line
Second line
The third line
I love Python
I love PHP
Text file processing
$./delete.py
$cat myfile
This is the first line
Second line
I love Python
I love PHP
Text file processing
$

Hope this script will be handy for some of you around .

One thought on “How to delete specific line in file using Python”

Leave a Reply

Your email address will not be published. Required fields are marked *