Home > Blockchain >  Check if a string has a certain value inside a file - python
Check if a string has a certain value inside a file - python

Time:08-13

I am working with python3 and I have a file (file.conf) where I have some variables.

The file.conf looks like this:

varx=true
vary=30015

varx can either be true or false (only). vary must be a numeric value between 30000 and 30099.

What would be the best way to create a small script to check if both vars exist and are well defined?

Note: I must get all the errors, if there are errors in both vars.

CodePudding user response:

I think you should look at the enter image description here

CodePudding user response:

Simple solution printing all errors:

with open("file.conf") as f:
    data = {k: v for k, _, v in (line.strip().partition("=") for line in f)}

if data["varx"] not in {"true", "false"}:
    print("varx must be true or false")

try:
    value = data["vary"] = int(data["vary"])
except ValueError:
    print("vary must be an integer")
else:
    if value < 30_000 or value > 30_099:
        print("vary Value must be between 30000 and 30099")

CodePudding user response:

Below is my solution using Pandas:

import pandas as pd


#Read from .conf file to a dataframe :

df = pd.read_csv('test.conf', sep='=', header=None, names=['key', 'value'])

# This 2 lines are just for visualy observing the dataframe 
# if you are using a notebook without "print"
print(df)
print('__'*8)


#First line below checks if there are any missing variable in the "value" column of the dataframe:

if df['value'].isnull().values.any():
    print('There is missing data')
else:
    print('No missing data')
    if df['value'][0] == 'True':        
        if 30000 <= int(df['value'][1]) <= 30999 :
            print('Everything is ok!')
            # after this point you can add your own tasks / functions if everything is ok
            # ...
        else:
            print('Var_y is out of range!')
     
    elif not 30000 <= int(df['value'][1]) <= 30999 :
        print('Both Var_x is not True! and Var_y is out of range!')        
    else:
        print('Var_x is not True!')

Will give you a nice result like this (tested from my terminal):

     key  value
0  var_x   True
1  Var_y  30054
________________
No missing data
Everything is ok!

or this :

     key  value
0  var_x   True
1  Var_y  40054
________________
No missing data
Var_y is out of range!

There is much room to play with this code...

CodePudding user response:

Using strtobool and some manual validation:

# Casue strtobool is deprecated :-(
def strtobool(s):
    if s.lower() in ['y', 't', 'true', '1', 'yes', 'on']:
        return True
    elif s.lower() in ['n', 'f', 'false', '0', 'no', 'off']:
        return False
    else:
        raise ValueError('invalid truth value %r' % (s,))

with open("file.conf") as f:
    data = {k: v for k, _, v in (line.strip().partition("=") for line in f)}

try:
    data["varx"] = strtobool(data["varx"])
    value = data["vary"] = int(data["vary"])
    if value < 30_000 or value > 30_099:
        raise ValueError("Value must be between 30000 and 30099")
except ValueError as e:
    print(f"Error: {e}")
    exit(1)

Different strtobool implementation:

import configparser

def strtobool(s):
    try:
        return configparser.ConfigParser.BOOLEAN_STATES[s.lower()]
    except KeyError as e:
        raise ValueError('Not a boolean: %s' % s) from e
  • Related