简体   繁体   English

Python用字符串检查文件内容

[英]Python checking file content with string

Hello! 你好! I have the following script: 我有以下脚本:

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")

It prints not equal, then I tried this method: 打印不相等,然后我试过这个方法:

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")

It also print not equal! 它也打印不相等! I want to store the content of autorun.inf file in script and every time i find such file I want to check its content if it is or not, I could not do, can anyone help me? 我想在脚本中存储autorun.inf文件的内容,每当我找到这样的文件时,我想检查它的内容是否有,我不能做,有人可以帮助我吗? the content of autorun.inf: autorun.inf的内容:

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

It is probably due to the fact that Windows new lines are \\r\\n instead of \\n . 这可能是因为Windows新行是\\r\\n而不是\\n Also, you should escape the "\\" , so instead use "\\\\" . 此外,你应该逃避"\\" ,所以改为使用"\\\\"

Linebreaks under Windows \\r\\n are different from Linux's \\n . Windows \\r\\n下的换行符与Linux的\\n

So try replacing \\n with \\r\\n . 所以尝试用\\n \\r\\n替换\\r\\n

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

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