-2

I am trying to parse go metafiles in the format of following:

require (
    github.com/cheggaaa/pb v1.0.28
    github.com/coreos/go-semver v0.2.0 // indirect
    github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e // indirect
    github.com/dustin/go-humanize v1.0.0
    github.com/fatih/color v1.7.0
        ...
        )

how do I get data between brackets and without using a regexp? (otherwise this noobish question would not exist at all). I have tried playing with split() but failed so far.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
Lorem
  • 39
  • 1
  • 3

3 Answers3

1

@rdas's suggestion of [l.strip() for l in file.readlines()[1:-1]] will work if the metafile is formatted like your example is. But really, you should just use regex. It's easier.

Alec
  • 8,529
  • 8
  • 37
  • 63
0

You can read the entire contents, split it into separate lines, then slice off the first and last lines:

with open(metafile) as f:
    requirements = f.read().splitlines()[1:-1]

Using with to open a file ensures it is closed properly when the scope ends.

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

Here is a code that should do it. It will copy all the lines between 'requiere (' and ')' as long as there are no other ')' in those blocks.

data file:

random stuff
require (
    github.com/cheggaaa/pb v1.0.28
    github.com/coreos/go-semver v0.2.0 // indirect
    github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e //indirect
    github.com/dustin/go-humanize v1.0.0
    github.com/fatih/color v1.7.0
        ...
        )



random stuff

out file :

github.com/cheggaaa/pb v1.0.28
github.com/coreos/go-semver v0.2.0 // indirect
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e //indirect
github.com/dustin/go-humanize v1.0.0
github.com/fatih/color v1.7.0
    ...

code :

f = open('data', 'r')
f2 = open('out', 'w')

toggle = False

for line in f:
    if 'require (' in line:
        toggle = True
        continue
    if toggle:
        if ')' in line:
            toggle = False
        else:
            f2.write(line)

f.close()
f2.close()
mlotz
  • 130
  • 3