搜索一行中的字符并将整行附加到列表中

时间:2017-10-01 18:56:11

标签: python

尝试通过查找文档ID来创建字典文件和发布列表文件。它应该打开文件并搜索术语' .I'并将该行作为列表元素

#Function which find the doc ID

#There is a list I created with name idList

def idTag():

file = open('cacm.txt', 'r')

line = file.readline()

while line:

if '.I' in line:

 idList.append(line)

elif not '.I' in line:

 line = file.readline()

elif not line:

 file.close()`

1 个答案:

答案 0 :(得分:3)

我不太明白你要做什么,但是如果我正确地阅读了这个问题,你想迭代文件的行,过滤那些包含字符串'.I'的文件。因此,这应该有效:

def idTag():
    # Create the list to collect the results in
    idList = []
    # Better way of opening a file;
    # closes it automatically when the `with` statement is finished
    with open('cacm.txt', 'r') as file:
        # Read each line from the file
        for line in file:
            # Filter those that have `.I` in them
            if '.I' in line:
                idList.append(line)
    return line

这利用了以下事实:文件可以循环,一次读取一行。