简体   繁体   中英

If “string” in variable: not working Python3

The problem: the string specified is not being found in the text file, why?

Description: I've got a simple Python script here that checks to see if a file exists, if it does, check the integrity, if it passes, stop. If it fails, recreate the file. If the file doesn't exist make it.

I've got everything working but the integrity check. The integrity check right now is simply looking for aa string called "[driveC]", I'd like to make it more thorough but this is what I've got going so far.

Any thoughts? A work around is to convert the config file into a list variable and search through the list for the string. But I'd like to use this method as it seems scalable.

My code: (also can be seen here https://hastebin.com/umitibigib.py ) line 55 is the check that is failing

###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()

The config file it's checking:

[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]

Your variable file is the file, not the contents of the file. You may want something like:

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

... which tests to see if that string is in the contents of the file.

What you originally had checks for an exact match on some line of the file, since the in operator will iterate over the file's lines. This didn't work because each line ends with a newline character, which you did not include in your target string. Like this:

if "[driveC]\n" in file:

If you need it to match exactly that text on a single line (with not even any whitespace on the same line), that will work. As a bonus, it will stop as soon as it finds the match instead of reading the whole file (although for smallish files, reading the whole file is probably just as fast or faster).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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