Python用字符串检查文件内容

时间:2011-09-12 17:19:06

标签: python

您好!我有以下脚本:

import os
import stat

curDir = os.getcwd()

autorun_signature = [ "[Autorun]",
                      "Open=regsvr.exe",
                      "Shellexecute=regsvr.exe",
                      "Shell\Open\command=regsvr.exe",
                      "Shell=Open" ]

content = []

def read_signature(file_path):
    try:
        with open(file_path) as data:
            for i in range(0,5):
                content.append(data.readline())
    except IOError as err:
        print("File Error: "+   str(err))

read_signature(os.getcwd()+'/'+'autorun.inf')

if(content==autorun_signature):
    print("Equal content")
else:
    print("Not equal")

它打印不相等,然后我尝试了这个方法:

import os
import stat

curDir = os.getcwd()

autorun_signature =  "[Autorun]\nOpen=regsvr.exe\nShellexecute=regsvr.exe\nShell\Open\command=regsvr.exe\nShell=Open"

content = ""

def read_signature(file_path):
    try:
        with open(file_path) as data:
            content = data.read()
    except IOError as err:
        print("File Error: "+   str(err))

read_signature(os.getcwd()+'/'+'autorun.inf')

if(content==autorun_signature):
    print("Equal content")
else:
    print("Not equal")

它也打印不相等! 我想在脚本中存储autorun.inf文件的内容,每当我找到这样的文件时,我想检查它的内容是否有,我不能做,有人可以帮助我吗? autorun.inf的内容:

[Autorun]
Open=regsvr.exe
Shellexecute=regsvr.exe
Shell\Open\command=regsvr.exe
Shell=Open

2 个答案:

答案 0 :(得分:1)

这可能是因为Windows新行是\r\n而不是\n。 此外,您应该转义"\",因此请使用"\\"

答案 1 :(得分:1)

Windows \r\n下的换行符与Linux的\n不同。

请尝试将\n替换为\r\n