Search code examples
pythonraspberry-piraspbianreadfile

Finding a number in a string on a specific line in Python


I am pushed with the challenge of creating a program that reads a text file. This program also needs to find certain things in the text file, I have already figured out how to do a basic read and search on the file. After it does the basic read and search it takes the most relevant information, and puts it into its respective text file. This is where it starts to get troubling. Lets say I am using the Raspi Config, the txt that I am reading will look like:

# Set sdtv mode to PAL (as used in Europe)
sdtv_mode=2
# Force the monitor to HDMI mode so that sound will be sent over HDMI cable
hdmi_drive=2
# Set monitor mode to DMT
hdmi_group=2
# Set monitor resolution to 1024x768 XGA 60 Hz (HDMI_DMT_XGA_60)
hdmi_mode=16
# Make display smaller to stop text spilling off the screen
overscan_left=20
overscan_right=12
overscan_top=10
overscan_bottom=10

After pulling all the variable names that I need, I then need to pull just the numbers out of this file. This is where I am stuck. Right now I am trying to find the numbers for just the over scans, I have it find where they all are, but I then need to know the value.

def findOverScan(beg, end):
    for num, line in enumerate(conf):
        if re.match("overscan(.*)", line):
            if num > beg and num < end:
                lineNum.append(num)

This allows me to find the line number. I am unsure of what I should do to find the number. I am not copying the entire thing and pasting it, as I am creating a file for another program to read for inputting everything into a database.

I open the config earlier on up int the program, as I use it multiple times, it didn't make sense to reopen it many times. the parameters for findOverScan are just beginning and ending lines for it to look through.


Solution

  • To parse your config file into a dict you can use

    def read_config(conf):
        config = {}
        for line in conf:
            line = line.strip()
            if line.startswith('#'):
                continue
            varname, value = line.split('=')
            config[varname] = value
        return config
    

    This gives you print(read_config(filecontent)):

    {'hdmi_drive': '2',
     'hdmi_group': '2',
     'hdmi_mode': '16',
     'overscan_bottom': '10',
     'overscan_left': '20',
     'overscan_right': '12',
     'overscan_top': '10',
     'sdtv_mode': '2'}
    

    You can add int(value) if all values are ints.