0xtvarun
0xtvarun

Reputation: 698

Reading for a specific value in a file

Just for practice I am writing a program in python to check version of the installed application from the .desktop entry in /usr/share/application/* is it possible to read a .desktop file just like any other text file? Also for the version I am looking for the 'version = ' entry in the file and read until it is end of integer for example

    X-GNOME-Bugzilla-Version=3.8.1
    X-GNOME-Bugzilla-Component=logview

so i want to be able to read only till 3.8.1 and not the next line

    applicationPath = '/usr/share/application'
    app = os.listdir(applicationPath)
    for package in app:
        if os.isfile(package):
            fileOb = open(applicationPath+'/'+package,'r')
            version = fileOb.read()
        elif os.isdir(package):
            app_list = os.listdir(applicationPath+'/'+package)

if it is possible to read a .desktop file

    version = fileOb.read() 

^will read the entire file, how do I get only the part I am looking for?

Upvotes: 0

Views: 40

Answers (1)

Adam Smith
Adam Smith

Reputation: 54203

Hoo-boy you've jumped into deep water here, huh? It's okay, luckily Python has very simple line-by-line operation. file objects yield their lines when iterated over, so:

for line in f:

gives you lines of the file. That means you can trivially expand your program to:

...
if os.isfile(package):
    with open(app_path + "/" + package) as f:
        # use this idiom instead. It saves you from having to close the file
        # and possibly forgetting (or having your program crash first!)
        for line in f:
            if "-Version=" in line:
                version = line  # do you want the whole line?
                                # or just "3.8.1"
                break  # no reason to read any more lines of the file
...

You could also use a regular expression, but it seems unnecessary in this case. It would look something like:

pat = re.compile(r"""
    (?:\w+-)+?      # some number of groups of words followed by a hyphen
    Version=        # the literal string Version=
    ([0-9.]+)       # capture the version number""", re.X)

...
for line in f:
    match = pat.match(line)
    if match:
        version = match.groups(1)
        break

Frankly I'd just use string operations to get your version number

for line in f:
    if "-Version=" in line:
        _, version = line.split("=")
        version = version.strip()  # in case there's trailing whitespace
        break

Upvotes: 1

Related Questions