Python-使用特定数据删除文件中的整行

Python-使用特定数据删除文件中的整行,python,Python,我来这里是因为我用尽了所有的资源来建立这个项目 我想用这样的特定数据删除一行文件 Code\t Name\t Colum2\t Colum3\t Colum4\t Colum5\n 我想根据代码删除整行 如果我键入代码,*.py将搜索包含此字符串的行并将其删除 有什么好灵魂能帮我吗?假设以下输入(在上生成)并保存为input.txt: 1 Jennifer O. Ingram P.O. Box 724, 4252 Arcu. St. 2 Lacy N. Fields 59

我来这里是因为我用尽了所有的资源来建立这个项目

我想用这样的特定数据删除一行文件

Code\t Name\t Colum2\t Colum3\t Colum4\t Colum5\n

我想根据代码删除整行

如果我键入代码,*.py将搜索包含此字符串的行并将其删除


有什么好灵魂能帮我吗?

假设以下输入(在上生成)并保存为input.txt:

1    Jennifer O. Ingram    P.O. Box 724, 4252 Arcu. St.
2    Lacy N. Fields    5998 Scelerisque Road
3    Blythe P. Abbott    Ap #251-2931 Magna. Rd.
4    Alyssa Y. Cobb    438-8110 Enim. Rd.
5    Peter Z. May    Ap #271-8340 Eget Avenue
6    MacKenzie A. Santos    8366 Nunc. St.
7    Kevyn C. Willis    Ap #583-9635 Erat Avenue
8    Nissim E. Ward    7606 Duis Rd.
9    Duncan J. Armstrong    Ap #164-282 Id, St.
10    Jesse B. Barnett    P.O. Box 742, 5758 Sagittis Street
以下代码将删除代码为5的行:

# Declare which code you want to delete.
# This can be further improved by being a parameter
# or read from outside the script.
code = 5
removed_lines = 0
f = open("input.txt","r+")
lines = f.readlines()
f.seek(0)
for line in lines:
    # Writes to the file all the lines except for those that
    # begin with the code declared above.
    if not line.startswith(str(code)):
        f.write(line)
    else:
        print("removed line %s" % line)
        removed_lines += 1
f.truncate()
f.close()
print("%d lines were removed" % removed_lines)
和input.txt将是:

1    Jennifer O. Ingram    P.O. Box 724, 4252 Arcu. St.
2    Lacy N. Fields    5998 Scelerisque Road
3    Blythe P. Abbott    Ap #251-2931 Magna. Rd.
4    Alyssa Y. Cobb    438-8110 Enim. Rd.
6    MacKenzie A. Santos    8366 Nunc. St.
7    Kevyn C. Willis    Ap #583-9635 Erat Avenue
8    Nissim E. Ward    7606 Duis Rd.
9    Duncan J. Armstrong    Ap #164-282 Id, St.
10    Jesse B. Barnett    P.O. Box 742, 5758 Sagittis Street

如果文件很大,则运行脚本可能需要更多的时间和资源。

您可以读取文件,然后以写模式打开它,只写开头没有该代码的行

//Open in read mode
f = open("yourfile.txt","r")
lines = f.readlines()
f.close()
//if code is 8
code = 8 
//Open in write mode
f = open("yourfile.txt","w")

for line in lines:
  arr = line.split('\t')
  if arr[0]!=code:   //Check for the code to avoid
    f.write(line)

f.close()

你能给我们一个输入和预期输出的例子吗?到目前为止你写了什么?你的问题有点含糊。你想看看是否删除了实际行吗?