简体   繁体   中英

Python - Remove entire Line in file using specific data

I'm here because i exhausted all my resources to built this program...

I want to delete a line of a file using specific data like this

Code \\t Name \\t Colum2 \\t Colum3 \\t Colum4 \\t Colum5 \\n

I want to delete entire line based on Code

if i type the code, the *.py will search the line thats contains this string and will delete it.

Can any good soul help me?

Assuming the following input (generated on generatedata.com ) and saved as input.txt:

1    Jennifer O. Ingram    P.O. Box 724, 4252 Arcu. St.
2    Lacy N. Fields    5998 Scelerisque Road
3    Blythe P. Abbott    Ap #251-2931 Magna. Rd.
4    Alyssa Y. Cobb    438-8110 Enim. Rd.
5    Peter Z. May    Ap #271-8340 Eget Avenue
6    MacKenzie A. Santos    8366 Nunc. St.
7    Kevyn C. Willis    Ap #583-9635 Erat Avenue
8    Nissim E. Ward    7606 Duis Rd.
9    Duncan J. Armstrong    Ap #164-282 Id, St.
10    Jesse B. Barnett    P.O. Box 742, 5758 Sagittis Street

the following code will remove line with code 5:

# Declare which code you want to delete.
# This can be further improved by being a parameter
# or read from outside the script.
code = 5
removed_lines = 0
f = open("input.txt","r+")
lines = f.readlines()
f.seek(0)
for line in lines:
    # Writes to the file all the lines except for those that
    # begin with the code declared above.
    if not line.startswith(str(code)):
        f.write(line)
    else:
        print("removed line %s" % line)
        removed_lines += 1
f.truncate()
f.close()
print("%d lines were removed" % removed_lines)

and input.txt will be:

1    Jennifer O. Ingram    P.O. Box 724, 4252 Arcu. St.
2    Lacy N. Fields    5998 Scelerisque Road
3    Blythe P. Abbott    Ap #251-2931 Magna. Rd.
4    Alyssa Y. Cobb    438-8110 Enim. Rd.
6    MacKenzie A. Santos    8366 Nunc. St.
7    Kevyn C. Willis    Ap #583-9635 Erat Avenue
8    Nissim E. Ward    7606 Duis Rd.
9    Duncan J. Armstrong    Ap #164-282 Id, St.
10    Jesse B. Barnett    P.O. Box 742, 5758 Sagittis Street

If the files are large, the run of the script can take more time and resources.

You can read the file and then open it in write mode, and only write the lines that don't have that code in the beginning.

//Open in read mode
f = open("yourfile.txt","r")
lines = f.readlines()
f.close()
//if code is 8
code = 8 
//Open in write mode
f = open("yourfile.txt","w")

for line in lines:
  arr = line.split('\t')
  if arr[0]!=code:   //Check for the code to avoid
    f.write(line)

f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM