读取文件中的特定值
问题描述:
仅供练习使用,我正在使用python编写程序以检查已安装应用程序的版本,该版本来自/ usr/share/application/*中的.desktop项。是否可以读取.desktop文件就像任何其他文本文件?另外对于版本我要找的“版本=”文件中的条目,并阅读直到例如整数结束读取文件中的特定值
X-GNOME-Bugzilla-Version=3.8.1
X-GNOME-Bugzilla-Component=logview
,所以我希望能够以只读至3.8.1,而不是下一行
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)
,如果它可以读取一个.desktop文件
version = fileOb.read()
^将读取整个文件,我怎么只得到了部分我在找?
答
Hoo-boy你在这里跳进了深水中,是吧?没关系,幸运的是Python有非常简单的逐行操作。 file
对象产生它们线路时遍历,所以:
for line in f:
为您提供了文件的行。这意味着你可以平凡扩大你的程序:
...
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
...
你也可以使用正则表达式,但它似乎在这种情况下没有必要。它看起来是这样的:
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
坦率地说我只用字符串操作,让您的版本号
for line in f:
if "-Version=" in line:
_, version = line.split("=")
version = version.strip() # in case there's trailing whitespace
break
我需要的只是3.8.1 – 0xtvarun
或者,也许只是'如果line.startswith(” X-GNOME-Bugzilla-Version'):fields = line.split('=')'并从那里取出(也许用'strip()'或者两个被引入来处理空格)。 – tripleee