Python从文件中删除一行行

标签 python file-handling

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

#!/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

时,文件将包含以下条目
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 multiple user args有关

最佳答案

让我指出您忽略的小事情。

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 来自动为您处理上下文。

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

  3. 你在写作时从未提及什么是YY

  4. 您可以在此处删除行,因为您试图一次性删除多行,因此 d = f.readlines() 应该是 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从文件中删除一行行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43613658/

相关文章:

python - django.contrib.admin 类似于 cherrypy 的应用程序

c - 在C中同时读取和写入文件

c - C 语言的文件处理计算

python - 使用 Python 在同一图中绘制两个猫图

python - 针对一维列表绘制单行二维 numpy 数组

Python Bokeh TapTool 跳转到对应DataTable行

image - Image::ValidJpeg 和内存文件的段错误

字符数组赋值

c++ - C 编程中的文件处理 : What is the difference between below two codes?

python - DatasetAutoFolds 的对象在 python 惊喜上没有属性 'global_mean'