如果包含某个单词,如何从 csv 中删除一行?

How to remove a line from a csv if it contains a certain word?

我有一个如下所示的 CSV 文件:

    2014-6-06 08:03:19, 439105, 1053224, Front Entrance
    2014-6-06 09:43:21, 439105, 1696241, Main Exit
    2014-6-06 10:01:54, 1836139, 1593258, Back Archway
    2014-6-06 11:34:26, 845646, external, Exit 
    2014-6-06 04:45:13, 1464748, 439105, Side Exit

我想知道如何删除包含单词 "external" 的行?

我在 SO 上看到另一个 post 解决了一个非常相似的问题,但我不完全理解...

我尝试使用类似这样的东西(如链接 post 中所述):

TXT_file = 'whatYouWantRemoved.txt'
CSV_file = 'comm-data-Fri.csv'
OUT_file = 'OUTPUT.csv'

## From the TXT, create a list of domains you do not want to include in output
with open(TXT_file, 'r') as txt:
    domain_to_be_removed_list = []

## for each domain in the TXT
## remove the return character at the end of line
## and add the domain to list domains-to-be-removed list
for domain in txt:
    domain = domain.rstrip()
    domain_to_be_removed_list.append(domain)


with open(OUT_file, 'w') as outfile:
    with open(CSV_file, 'r') as csv:

        ## for each line in csv
        ## extract the csv domain
        for line in csv:
            csv_domain = line.split(',')[0]

            ## if csv domain is not in domains-to-be-removed list,
            ## then write that to outfile
            if (csv_domain not in domain_to_be_removed_list):
                outfile.write(line)

文本文件只有一个词 "external" 但它不起作用....我不明白为什么。

发生的事情是程序会运行,并且会生成output.txt,但什么都不会改变,没有带"external"的行被取出。

我正在使用 Windows 和 python 3.4,如果它有所不同的话。

抱歉,如果这看起来是一个非常简单的问题,但我是 python 的新手,非常感谢这方面的任何帮助,谢谢!!

看起来你在拆分行后正在抓取第一个元素。根据您的示例 CSV 文件,这将为您提供日期。

您可能想要的(同样,假设示例是它始终有效的方式)是获取第三个元素,所以像这样:

csv_domain = line.split(',')[2]

但是,正如其中一条评论所说,这不一定是万无一失的。您假设 none 个单元格中有逗号。根据您的示例,这可能是一个安全的假设,但通常在处理 CSV 文件时,我建议使用 Python csv module.

如果你可以使用其他东西,那么 python,grep 会像这样工作:

grep file.csv "some regex" > newfile.csv

只会给你匹配正则表达式的行,而:

grep -v file.csv "some regex" > newfile.csv 

除了与正则表达式匹配的行外,给出了所有内容

将输出重定向到新文件。它会给你每一行,除了那些包含 "external"

import sys
import re

f = open('sum.csv', "r")
lines = f.readlines()

p = re.compile('external')

for line in lines:
    if(p.search(line)):
        continue
else:
    sys.stdout.write(line)