从列表写行到文件中搜索变量

时间:2016-08-17 21:31:38

标签: python

使用for x in list查看列表时,我遇到了问题:

if x in Invalid_names_file:
    ISP_names_file.write(str(x))

如果我将if替换为for,那么我会将Invalid_names_file的全部内容写入ISP_names_file

这是我的代码:

def isp_email_names():
    with open('Invalid_names_file', 'r') as Invalid_names_file:
        with open('ISP_names_file', 'w') as ISP_names_file:
            for x in one_ip_each():
                if x in Invalid_names_file:
                    ISP_names_file.write(str(x))
                    ISP_names_file.flush()
        ISP_names_file.closed
    Invalid_names_file.closed

one_ip_each变量是我的列表,来自我导入的模块。

我可以在脚本的末尾打印此列表,以确保它正常工作,但无法在写入文件中输入任何内容。

我将在此后面添加更多for个语句,所以我不介意它只是我列表中显示的最后一个x当我将其剪切掉时看到它正在发挥作用。

该文件确实写入磁盘,其中没有if ...,整个文件-1和for ...

我应该在原帖中更清楚。

我的清单 - >

['192.168.122.21', '192.168.122.22', '192.168.122.25']

和我试图通过的一些文件 - >

Jul 25 11:29:02 testing sshd[1345]: Invalid user JoseMartinez from 192.168.122.25
Jul 25 11:29:03 testing sshd[1347]: Invalid user BillyCarter from 192.168.122.25
Jul 25 11:24:26 testing sshd[1094]: Invalid user DavidFlores from   192.168.122.21
Jul 25 11:25:05 testing sshd[1108]: Invalid user Nicole from 192.168.122.22

尝试'为列表中的x'找到包含x的行并将整行打印到文件中。

3 个答案:

答案 0 :(得分:0)

Invalid_names_file是一个迭代器。因此,在第一个if x in ...之后,此迭代器为空,所有后续测试都会生成False。首先将您的文件读入列表,然后使用in运算符测试每一行,而不仅仅是列表元素。

def isp_email_names():
    with open('Invalid_names_file', 'r') as Invalid_names_file:
        Invalid_names_file = list(Invalid_names_file)
    with open('ISP_names_file', 'w') as ISP_names_file:
        for ip in one_ip_each():
            for line in Invalid_names_file:
                if ip in line:
                    ISP_names_file.write(line)

答案 1 :(得分:0)

一个不太优雅的解决方案,在O(N)运行时运行,但检查x是否包含在readline中。对不太优雅的解决方案提前抱歉,希望它有效。

def isp_email_names():
    with open('Invalid_names_file', 'r') as Invalid_names_file:
        with open('ISP_names_file', 'w') as ISP_names_file:
            for x in one_ip_each():
                if str(x) in Invalid_names_file.readline():
                    ISP_names_file.write(str(x))
                    ISP_names_file.flush()

答案 2 :(得分:0)

最终代码 - >>

def isp_email_names():
    with open('Invalid_names_file', 'r') as Invalid_names_file:
        with open('ISP_names_file', 'w') as ISP_names_file:
            for x in one_ip_each():
                for line in Invalid_names_file:
                    if x in line:
                        ISP_names_file.writelines(str(line))
                        ISP_names_file.flush()
            ISP_names_file.closed
        Invalid_names_file.closed

isp_email_names()

我不知道为什么我必须调用该函数才能将其写入磁盘。我会试着稍后解决这个问题。

感谢大家的耐心等待。