1

我正在尝试读取输入文件并匹配包含“ToolVersionEdit”的行,然后根据“=”拆分并获取第二部分..我正在使用以下内容..没有得到所需的输出..我在哪里出错了?输入和预期输出如下

输入:

[BuildRequest]
BuildRequestVersion=4.4.21
BuildRequestType=Phone
BuildCommandComboBox=common/build/build.sh tz:A8064AAAAANAAT140029.1 tz_bid=AAAAANAA wcnss:A8064AAAAANAAW120072.1 wcnss_bid=SCAQBAF lpass:A8064AAAAANAZL140106.1 boot_9x15:M9615ACETRMAAB12171.1 boot_9x15_bid=ACEHRMAA rpm:A8064AAAAANAAR1100153.1 rpm_bid=AAAAANAAR modem_9x15:M9615ACEFWTAAM4010223.1 modem_9x15_bid=ACEFWTAA apps_9x15:M9615AFEHRMAA2745.1 apps_9x15_bid=AFEHRMAA rpm_9x15:M9615ACETRMAAR1100159.4 rpm_9x15_bid=AAAAANAAR boot:A8064AAAAANAAB12171.1 boot_bid=AAAAANAA lpass_9x15:M9615ACETRMAZL140105.3 apps:A8064AAAAANLGA2214074.1 dsps:A8064AAAAANAAS150007.1 dsps_bid=DSPSBLD
ToolVersionEdit=1.6.21
CheckSumCheckBox=0
PurposeEdit=
[BuildRequestComments]
LineCount=0

预期输出:-1.6.21

import re
import sys
file = "C:\Dropbox\Reference.brf"

lines = open(file ,'r').readlines()

for line in lines:
    if 'ToolVersionEdit' in line:
        line = line.strip('=')[1]

print line
4

5 回答 5

3

您的问题是您正在覆盖line变量。您使用的变量与您尝试缓存的循环变量相同。此外,一旦你找到了你要找的东西,你就不需要继续循环了。

我所做的另一项更改是删除对readlines. 您可以直接从文件对象遍历所有行。此外,(可能)file用变量覆盖模块是一种不好的形式,所以我也重命名了那个。

import re
import sys
filename = "C:\Dropbox\Reference.brf"
try:
    input_file = open(filename ,'r')
except IOError as exc:
    print exc
else:
    cached_line = ""
    for line in input_file:
        if 'ToolVersionEdit' in line:
            cached_line = line.split('=')[1]
            break

    print cached_line
于 2012-12-13T00:00:22.857 回答
2

使用配置解析器。您的文件的构造是 unix 配置文件,并且 ConfigParser(python3 中的 configparser)可以读取并解析它http://docs.python.org/2/library/configparser.html

from ConfigParser import RawConfigParser as Parser

filename = 'yourfile.conf'

config = Parser()
config.read(filename)
print config.get('BuildRequest', 'ToolVersionEdit')

如果您愿意,可以通过以下代码获得所有选项:

for section in config.sections():
    for option, value in config.items(section):
        print value
于 2012-12-13T00:41:31.260 回答
1

You need actually two things.

  1. Change strip to split
  2. break after you split it.

Resultant code looks like this,

 7  for line in lines:
 8      if 'ToolVersionEdit' in line:
 9          line = line.split('=')[1]
10          break
于 2012-12-13T00:03:49.137 回答
1

Try this:

    import re
    import sys
    file = "/tmp/abc.txt"

    lines = open(file ,'r').readlines()

    for line in lines:
        if 'ToolVersionEdit' in line:
            desired_line = line.split('=')[1]

print desired_line

于 2012-12-13T00:04:04.420 回答
1

你想使用split而不是strip

于 2012-12-13T00:00:12.537 回答