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

时间:2015-04-22 15:25:55

标签: python

我在这里,因为我用尽了所有资源来构建这个程序......

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

代码\ t名称\ t Colum2 \ t Colum3 \ t Colum4 \ t Colum5 \ n

我想根据代码

删除整行

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

任何善良的灵魂能帮助我吗?

2 个答案:

答案 0 :(得分:2)

假设以下输入(在generatedata.com上生成)并保存为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

如果文件很大,脚本的运行可能会花费更多的时间和资源。

答案 1 :(得分:0)

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

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