本文介绍了删除线图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从具有特定模式的csv中删除一行。
I need to remove a line from a csv with a specific pattern
这是我的csv文件的外观。
this is how my csv file looks.
lbm,16730,0
namd,16733,6
namd,16731,2
namd,16732,4
如果我想删除模式 16730
所以,输出结果如下:
namd,16733,6
namd,16731,2
namd,16732,4
我如何做到这一点?
这里是一个小的脚本我在互联网上的一些文件的帮助下写的
here is a small script I wrote with the help of some files on the internet
def delete_line(dello):
opener = open(input_csv, 'rb')
dataset = csv.reader(opener, delimiter=',')
output = []
for line in dataset:
if 'dello' == line[1]:
print line[1]
#i dont know how to strip it here
output.append(line)
opener.close()
fn = input_csv
f = open(fn,'w')
f.writelines(output)
f.close()
any
推荐答案
如果您需要python,请使用:
If you need python, then use this:
def delete_line(dello):
data = open("abc.csv").readlines()
i = 0
for line in data:
if dello in line:
data.pop(i)
i += 1
open("abc.csv", "w").write("".join(data))
delete_line("16732")
$ b b
输入:
Input:
lbm,16730,0
namd,16733,6
namd,16731,2
namd,16732,4
输出:
lbm,16730,0
namd,16733,6
namd,16731,2
注意:这将删除所有匹配字符串的条目。
Note: this will remove all the entries matching the string.
更新
修改您的验证码:
import csv
def delete_line(dello):
opener = open("abc.csv", 'rb')
dataset = csv.reader(opener, delimiter=',')
output = []
for line in dataset:
# Add to output only if not matching the string
if dello != line[1]:
# Need join as line is a list
output.append(",".join(line) + "\n")
opener.close()
fn = "abc.csv"
f = open(fn,'w')
f.writelines(output)
f.close()
delete_line("16730")
如果您需要删除条目,您可以使用 dataset.pop(index)
。
If you need to strip out an entry, you can use dataset.pop(index)
.
这篇关于删除线图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!