如果;“字符串”;变量中:不工作的Python3
问题:在文本文件中找不到指定的字符串,为什么 描述:我这里有一个简单的Python脚本,检查文件是否存在,如果存在,检查完整性,如果通过,停止。如果失败,请重新创建该文件。如果文件不存在,请创建它 除了完整性检查,我什么都做了。现在的完整性检查只是寻找一个名为“[driveC]”的字符串,我想让它更彻底,但这就是我到目前为止所做的 有什么想法吗?解决方法是将配置文件转换为列表变量,并在列表中搜索字符串。但是我想使用这个方法,因为它看起来是可伸缩的 我的代码:(也可以在这里看到)第55行是失败的检查如果;“字符串”;变量中:不工作的Python3,python,python-3.x,Python,Python 3.x,问题:在文本文件中找不到指定的字符串,为什么 描述:我这里有一个简单的Python脚本,检查文件是否存在,如果存在,检查完整性,如果通过,停止。如果失败,请重新创建该文件。如果文件不存在,请创建它 除了完整性检查,我什么都做了。现在的完整性检查只是寻找一个名为“[driveC]”的字符串,我想让它更彻底,但这就是我到目前为止所做的 有什么想法吗?解决方法是将配置文件转换为列表变量,并在列表中搜索字符串。但是我想使用这个方法,因为它看起来是可伸缩的 我的代码:(也可以在这里看到)第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()
变量
file
是文件,而不是文件的内容。您可能需要以下内容:
if "[driveC]" in file.read():
。。。测试该字符串是否在文件内容中
您最初使用的是在文件的某一行上检查精确匹配,因为中的操作符将迭代文件的行。这不起作用,因为每行都以换行符结尾,而您的目标字符串中没有包含换行符。像这样:
if "[driveC]\n" in file:
如果您需要它在一行上精确匹配该文本(在同一行上甚至没有任何空格),这将起作用。作为奖励,它将在找到匹配项后立即停止,而不是读取整个文件(尽管对于较小的文件,读取整个文件可能同样快或更快)。您的变量file
是文件,而不是文件的内容。您可能需要以下内容:
if "[driveC]" in file.read():
。。。测试该字符串是否在文件内容中
您最初使用的是在文件的某一行上检查精确匹配,因为
中的操作符将迭代文件的行。这不起作用,因为每行都以换行符结尾,而您的目标字符串中没有包含换行符。像这样:
if "[driveC]\n" in file:
如果您需要它在一行上精确匹配该文本(在同一行上甚至没有任何空格),这将起作用。作为奖励,它会在找到匹配项时立即停止,而不是读取整个文件(虽然对于较小的文件,读取整个文件可能同样快或更快)。它也不是在
位中实际查找它实际上,它是在各行上迭代查找精确的匹配项好的,然后它在搜索什么?read()方法是否将整个文件转换为要搜索的字符串对象?是的,read()
将整个内容作为字符串获取。我已经更新了我的答案,补充了一些关于如何让它和行匹配一起工作的信息。啊哈,我忘记了那个新的行字符。非常感谢您的详细解释,在文件中使用if“[driveC]\n”进行测试:也可以正常工作。太棒了。它实际上也不是在
位中寻找它。实际上,它是在各行上迭代寻找一个精确的匹配项。好吧,它在搜索什么?read()方法是否将整个文件转换为要搜索的字符串对象?是的,read()
将整个内容作为字符串获取。我已经更新了我的答案,补充了一些关于如何让它和行匹配一起工作的信息。啊哈,我忘记了那个新的行字符。非常感谢您的详细解释,在文件中使用if“[driveC]\n”进行测试:也可以正常工作。极好的