2

I have a file which has some lines of:

FS "name" machine:"path"
{
}

which I want to read whatever comes after FS and return each parameter. I mean return should be name, machine and path.

Name:
    "/PF/B/"
    "/PF/A/"

Machine:
    FFFFFF..
    XXXXXX…

Path:
    “/PF/J”
    “/PF/K”

The code:

Def parse()
with open (myfile.txt) as f:
    for line in f:
if line.strip().startswith(‘FS’)
            Name = []
            Machine = []
            Path = []
????

Any help would be appreciated.

3 Answers 3

4

You might use a regular expression,

import re
with open('myfile.txt') as f:
    found = re.findall(r'^FS\s*"([^"]*)"\s*([^:]*)\s*:\s*"([^"]*)"',f.read(),re.MULTILINE)
names, machines, paths = zip(*found)

EDIT : check if 'FS' is at the beginning of a line

EDIT2 : works with possible spaces between search patterns

Sign up to request clarification or add additional context in comments.

Comments

3

I would use a regular expression to match those lines, storing the results as I go:

import re

results = []
with open ('myfile.txt') as f:
  for line in f:
    match = re.match(r'FS\s+(".*?")\s+(.*?):(".*?")', line)
    if match:
      results.append(match.groups())

if results:
  print 'Name:\n' + '\n'.join('    '+result[0] for result in results)
  print 'Machine:\n' + '\n'.join('    '+result[1] for result in results)
  print 'Path:\n' + '\n'.join('    '+result[2] for result in results)

Comments

0

Use the re module:

line = "FS "name" machine:"path""
for n in re.split(" ", line)
    print(n)

Will print:

FS

"name"

machine

"path"

EDIT: sorry the last one would print machine:"path" and then you'll have to do re.split(":", n) and then it will print machine and then "path"

2 Comments

So long as neither name, machine, nor path ever contain spaces. The other answers are a lot more robust.
you said that how your file looks like so I gave you an answer according to that, if you want a more robust answer give a more accurate description...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.