Python从文件中删除一行代码 [英] Python deleting a block of lines from a file

查看:222
本文介绍了Python从文件中删除一行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力弄清楚应该如何从文件中删除一行代码.下面是代码

I'm struggling to figure out as to how I should go about deleting a block of lines from a file. Below is the code

#!/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:端口:名称).当脚本以./script.py 192.168.0.10:80:string 192.168.0.10:80:string

As you can see I'm appending the file.txt with user inputs. i.e (format:ip:port:name). File will contain below entries when the script is excuted as ./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

现在,当用户输入的输入方式相同时,我想从file.txt中删除行.通过运行以上代码,什么都不会发生.我是一个初学者,如果您能帮助我理解的话,我会非常感激.此问题与 python多用户args

Now I want to delete the line(s) from file.txt when the user input is given the same way. With the above code being run nothing happens. I'm a beginner and really appreiciate if you help me understand. This question is related to python multiple user args

推荐答案

让我指出您缺少的小东西.

Let me point out the little things you are missing.

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()

  1. 您在循环内部打开了文件,然后在外部关闭了文件.文件对象超出范围.使用with会自动为您处理上下文.

  1. You opened the file inside the loop and closing outside. The file object is out of scope. Use with which handles the context automatically for you.

在循环中打开文件是个坏主意,因为它会创建很多文件描述符,从而消耗大量资源.

It is a bad idea to open a file inside a loop, because it will create so many file descriptor which consumes a lot of resources.

在编写时您从未提及YY是什么.

You never mentioned what is YY when you are writing.

您可以在此处删除行,因为您要尝试一次删除多行,因此d = f.readlines()应该为d = f.read()

You can delete lines here as you are trying to delete multiple lines in one go, so d = f.readlines() should be d = f.read()

下面是更新的代码.

#!/usr/bin/python
import argparse
import re
import string

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 # ['192.168.1.10:80:name1', '172.25.16.2:100:name3']


def getStringInFormat(ip, port, name):
    formattedText = "HOST Address:{ip}:PORT:{port}\n"\
                    "mode tcp\n"\
                    "bind {ip}:{port} name {name}\n\n".format(ip=ip, 
                                                                port=port, 
                                                                name=name)

    return formattedText

# Writing the content in the file
# with open("file.txt", "a") as myfile:
#    for kkk in kkk_list:
#         ip, port, name = re.split(":|,", kkk)
#         myfile.write(getStringInFormat(ip, port, name))



with open("file.txt", "r+") as f:
    fileContent = f.read()

    # below two lines delete old content of file
    f.seek(0)
    f.truncate()

    # get the string you want to delete
    # and update the content
    for kkk in kkk_list:
        ip, port, name = re.split(":|,", kkk)

        # get the string which needs to be deleted from the file
        stringNeedsToBeDeleted = getStringInFormat(ip, port, name)

        # remove this from the file content    
        fileContent = fileContent.replace(stringNeedsToBeDeleted, "")

    # delete the old content and write back with updated one
    # f.truncate(0)
    f.write(fileContent)

# Before running the script file.txt contains 

# HOST Address:192.168.1.10:PORT:80
# mode tcp
# bind 192.168.1.10:80 name name1
#
# HOST Address:172.25.16.2:PORT:100
# mode tcp
# bind 172.25.16.2:100 name name3

# After running file.txt will be empty
# as we have deleted both the entries.

这篇关于Python从文件中删除一行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆