的Python - 删除文件全线使用特定的数据
问题描述:
我来这里是因为我耗尽了我所有的资源来建造这个节目......的Python - 删除文件全线使用特定的数据
我想删除使用特定的数据这样
一个文件的行编号\ t姓名\ t Colum2 \ t Colum3 \ t Colum4 \ t Colum5 \ n
我想删除基于代码
整行,如果我键入鳕鱼e,* .py将搜索包含此字符串的行,并将其删除。
任何好的灵魂能帮助我吗?
答
假设下面的输入(上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
如果文件很大,脚本的运行可能需要更多的时间我和资源。
+0
你解决了我工作中的4个问题。 –
+0
你想查看是否有实际的行被删除? – AllBlackt
答
您可以读取文件,然后在写入模式下打开它,并且只写入在开始时没有该代码的行。
//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()
你能给我们一个示例输入和预期输出吗?你到目前为止写的是什么?你的问题有点含糊。 –