我正在努力弄清楚我该如何去从文件中删除一行代码块。下面是代码Python从文件中删除一行代码
#!/usr/bin/python
import argparse
import re
import string
##getting user inputs
p = argparse.ArgumentParser()
p.add_argument("input", help="input the data in format ip:port:name", nargs='*')
args = p.parse_args()
kkk_list = args.input
def printInFormat(ip, port, name):
formattedText = '''HOST Address:{ip}:PORT:{port}
mode tcp
bind {ip}:{port} name {name}'''.format(ip=ip,
port=port,
name=name)
textWithoutExtraWhitespaces = '\n'.join([line.strip() for line in formattedText.splitlines()])
# you can break above thing
# text = ""
# for line in formattedText.splitlines():
# text += line.strip()
# text += "\n"
return(formattedText)
#####here im writing writing the user inoput to a file and it works great.
#with open("file.txt", "a") as myfile:
# for kkk in kkk_list:
# ip, port, name = re.split(":|,", kkk)
# myfile.write(printInFormat(ip, port, name))
###### here is where im struggling.
for kkk in kkk_list:
ip, port, name = re.split(":|,", kkk)
tobedel = printInFormat(ip, port, name)
f = open("file.txt", "r+")
d = f.readlines()
f.seek(0)
if kkk != "tobedel":
f.write(YY)
f.truncate()
f.close()
正如你可以看到我用追加用户输入的file.txt的。即(格式:ip:port:name)。文件将包含以下条目时,脚本excuted为./script.py 192.168.0.10:80:string 192.168.0.10:80:string
Host Address:192.168.0.10:PORT:80
mode tcp
bind 192.168.0.10:80 abc
Host Address:10.1.1.10:PORT:443
mode tcp
bind 10.1.1.10:443 xyz
现在我想删除文件中的线(S)。 txt当用户输入以同样的方式给出时。上面的代码运行没有任何反应。如果你能帮助我理解,我是一个初学者,真的很友善。此问题与python multiple user args
你想删除什么?你能解释一下吗?可能会有相同的例子。从代码中不太清楚。 – arunk2
@ArunKumar我试图删除第二个代码窗口中提到的那两个块。当脚本运行参数::它应该从file.txt中删除相应的条目。谢谢。 –
bindo