如果变量中的“string”:不工作Python3

时间:2017-04-07 21:25:54

标签: python python-3.x

问题:在文本文件中找不到指定的字符串,为什么?

描述:我这里有一个简单的Python脚本,它检查文件是否存在,如果存在,检查完整性,如果通过,则停止。如果失败,请重新创建该文件。如果该文件不存在,请填写。

我已经完成了所有工作但是完整性检查。现在的完整性检查只是寻找一个名为“[driveC]”的字符串,我想让它更彻底,但这是我到目前为止所做的。

有什么想法?解决方法是将配置文件转换为列表变量,并在列表中搜索字符串。但是我想使用这种方法,因为它似乎可以扩展。

我的代码:(也可以在这里看到https://hastebin.com/umitibigib.py第55行是失败的支票

###io testing
import os.path

try:
    from configparser import ConfigParser
except ImportError:
    from ConfigParser import ConfigParser  # ver. < 3.0

#variables

drives_given = [ 'C', 'D']    

# instantiate config parser
config = ConfigParser()
cfg_path = os.path.exists('smartPyConfig.ini')

#A config file was not found, let's make one
def create_config_file():
    cfgfile = open("smartPyConfig.ini",'w')
    print("A new config file was created")
    print("")
    print("Adding thresholds and drive sections")

    #Add general settings
    config.add_section('general')
    config.set('general', 'logging_level', 'debug')

    #Add smartctl threshold values
    config.add_section('standard_thresholds')
    config.set('standard_thresholds', 'threshold_value_raw_read_error_rate_norm', '101')
    config.set('standard_thresholds', 'threshold_value_reallocated_sector_count_norm', '105')
    config.set('standard_thresholds', 'threshold_value_seek_error_rate_norm', '101')
    config.set('standard_thresholds', 'threshold_value_power_on_hours_raw', '1000')
    config.set('standard_thresholds', 'threshold_value_temperature_celsius_raw', '100')
    config.set('standard_thresholds', 'threshold_value_reported_uncorrect_raw', '100')
    config.set('standard_thresholds', 'threshold_value_hardware_ecc_recovered_norm', '100')
    config.set('standard_thresholds', 'threshold_value_offline_uncorrectable_raw', '100')
    config.set('standard_thresholds', 'threshold_value_free_fall_sensor_raw', '100')
    config.set('standard_thresholds', 'threshold_value_udma_crc_error_count_norm', '350')
    #DONE

#Create a section for each drive we were given
    #for every drive letter listed in the drives_given list, make a section for it
    for i in drives_given:
        config.add_section('drive%s' % i)

    #Write out the data and close the file
    config.write(cfgfile)
    cfgfile.close()
    print("Config file created and written to disk.")

#Check to see if file is healthy, if not recreate it.
def check_file_integrity():
    with open("smartPyConfig.ini", 'r') as file:
        if "[driveC]" in file: #Not working
            print("found drive C in config file.")
            print("finished")
        else:
            print("drive C not found in config file.")
            create_config_file()

#check for a config file
def check_for_config():    
    # Check to see if the file exists
    try:
        if cfg_path: #if cfg_path is true (true = the file was found) do this
            print("Config file found!")
            print("Checking config file..")
            check_file_integrity()
        else: #if cfg_path is not true, file was not found, do this
            print("Config file not found")
            print("Creating config file.")
            create_config_file()
    except Exception as e: 
        print("An exception occured, printing exception")
        print(e)


check_for_config()

它正在检查的配置文件:

[general]
logging_level = debug

[standard_thresholds]
threshold_value_raw_read_error_rate_norm = 101
threshold_value_reallocated_sector_count_norm = 105
threshold_value_seek_error_rate_norm = 101
threshold_value_power_on_hours_raw = 1000
threshold_value_temperature_celsius_raw = 100
threshold_value_reported_uncorrect_raw = 100
threshold_value_hardware_ecc_recovered_norm = 100
threshold_value_offline_uncorrectable_raw = 100
threshold_value_free_fall_sensor_raw = 100
threshold_value_udma_crc_error_count_norm = 350

[driveC]

[driveD]

1 个答案:

答案 0 :(得分:3)

您的变量file是文件,而不是文件的内容。你可能想要这样的东西:

if "[driveC]" in file.read():

...测试该字符串是否在文件内容中。

您最初检查文件某些行的完全匹配,因为in运算符将迭代文件的行。这不起作用,因为每一行都以换行符结尾,您没有将其包含在目标字符串中。像这样:

if "[driveC]\n" in file:

如果你需要它在一行上完全匹配该文本(在同一行上甚至没有任何空格),那将是有效的。作为奖励,它会在找到匹配后立即停止,而不是读取整个文件(尽管对于较小的文件,读取整个文件的速度可能同样快或者更快)。