繁体   English   中英

从文件中查找包含另一个文件内容的行Python

[英]find lines from a file with the content of another file Python

所以..这就是我想要做的..对于数据文件中的每一行,请检查其他文件是否包含此字符串。

我尝试了其他帖子中的一些内容,但都不是一件好事。

下面的代码说,即使它们存在于文件中的某个位置,它也找不到任何要查找的字符串。

def search():
    file1= open('/home/example/file1.txt', 'r')
    datafile= open('/home/user/datafile.txt', 'r')

    for line in datafile:
        if line in file1:
            print '%s found' % line
        else:
            print '%s not found' % line

search()

假设第一个文件的内容不是很大,您可以将整个文件读取为字符串,然后使用字符串包含进行检查:

def search():
    file1_content = open('/home/example/file1.txt').read()
    datafile = open('/home/user/datafile.txt')

    for line in datafile:
        if line in file1_content:
            print '%s found' % line
        else:
            print '%s not found' % line

请注意, open的默认模式是'r' ,因此,如果您以文本模式阅读,则实际上不需要传递该参数。

您可以将文件读入一set ,然后检查是否包含在第二个文件中。 set的通常在检查包含列表时更快。

def search():
    file1 = set(open('/home/example/file1.txt'))
    datafile= open('/home/user/datafile.txt', 'r')

    for line in datafile:
        if line in file1:
            print '%s found' % line
        else:
            print '%s not found' % line

您还可以使用设置操作来提取例如不在第一个文件中的所有行:

set(open('/home/user/datafile.txt', 'r')) - set(open('/home/example/file1.txt'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM