spoke
spoke

Reputation: 267

Python File Parser

This is a model of a text file that I want to parse:

Something: different

Date: 22:23:32

I want to get the information after the :, for example: different and 22:23:32.

The only way in which I know how to do it, is to parse each line and split after :. The problem is that in case of date, it will crash.

This is the code I have written up to now:

for line in file:
    if re.match("Something", line):
        line = line.split(':')
        print (str(line[1]))
    elif re.match("Date", line):
        ???

This is just a simple example, the file which I need to parse containing much more information that I need to extract.

Which would be the most efficient way to solve the problem?

Upvotes: 0

Views: 90

Answers (2)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

Use second parameter of split method, it allows you to avoid problem with few : in one line, see code below:

for line in file:
    data = line.split(':', 1)[1]
    print data

str.split([sep[,maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

Source: python documentation

Upvotes: 2

zondo
zondo

Reputation: 20336

You need to specify a limit with split():

line = line.split(':', 1)

This way, this:that:somethingelse is interpreted as ['this', 'that:somethingelse'].

Upvotes: 3

Related Questions