简体   繁体   中英

how to delete line from a txt file containg “- - ” and : in python

Have a txt files with below data need to deleted all the lines which have ":" and "---"

Name                        
DR_CNDBAIRTAPZP4_GPFS_VOL.0
0:1:3
DR_CNDBAIRTAPZP4_GPFS_VOL.1 
DR_CNDBAIRTAPZP40_VOL.0 
-----
0:1:3
8:9:2
server2
-----
1:1:2
server6

OutPut file
DR_CNDBAIRTAPZP4_GPFS_VOL.0
DR_CNDBAIRTAPZP4_GPFS_VOL.1 
DR_CNDBAIRTAPZP40_VOL.0
server2
server6

You can write a function to remove specific lines from the text file as below:

    def deleteTheLine():
       f = open('data.txt') // add your text file here
       output = []
       str="----" // string that you want to remove
       for line in f:
          if not line.startswith(str):
            output.append(line)
       f.close()
       f = open('data.txt', 'w')
       f.writelines(output)
       f.close()

   deleteTheLine()

may be you can do this reading line by line into file and check presence of: and -

import os
with open(os.path.join(input_file),'r') as f1 :
    with open(os.path.join(output_file),'w') as f2 :
        temp = f1.readlines()
        for line in temp:
            print(line)
            if '-' not in line and ':' not in line :
                f2.write(line)

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