Skip to main content
 首页 » 编程设计

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

2025年05月04日53itcoder

我有一个看起来像这样的 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 

我想知道如何删除包含“外部”一词的行?

我在 SO 上看到另一个 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) 

文本文件只有一个词“外部”,但它不起作用....我不明白为什么。

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

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

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

请您参考如下方法:

将输出重定向到一个新文件。它会给你每一行,除了那些包含“外部”的行

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)