[英]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 "---"有一个包含以下数据的txt文件需要删除所有带有“:”和“---”的行
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:您可以编写 function 从文本文件中删除特定行,如下所示:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.