3

I have a config file like this:

asaasdfg fdhshs "kgk jjjd" jdyesgs
gdgdg urur "irit jhd *" djjdj
trteyuueu ueue "jyuoro" ooyoy

and so on. I am able to parse it using my own parser module (using regex) but that assumes a strict structure for the file (e.g. elements in each row separated by a single whitespace). Is there a general python module for parsing such files so that it won't matter how many whitespaces separate the elements.

I have looked at this but it assumes a different file structure than what I have. In particular, I don't have sections or key:value pairs.

Any suggestions?

4
  • 6
    Why use a custom format? Use JSON for configs humans won't edit, and either INI (with ConfigParser) or YAML for those humans will edit. Commented Jul 31, 2012 at 18:01
  • 1
    well I am given the config files and I'm not the one creating them. Commented Jul 31, 2012 at 18:04
  • 2
    a combination of the CSV module and namedtuple is one option. The CSV module supports several options to handle quoted strings. Commented Jul 31, 2012 at 18:06
  • @Colin, or you could just use straight Python like Django does. Since there is no need to recompile Python code, there really isn't a compelling reason to store your config in a different format like you would with Java or C. Commented Jul 31, 2012 at 18:33

1 Answer 1

4

While it's not completely clear what you need, the shlex module will happily parse things like quoted strings in ways that generally make sense. For example, given your sample input, the following code:

for line in sys.stdin:
    parts = shlex.split(line)
    print parts

Will produce:

['asaasdfg', 'fdhshs', 'kgk jjjd', 'jdyesgs']
['gdgdg', 'urur', 'irit jhd *', 'djjdj']
['trteyuueu', 'ueue', 'jyuoro', 'ooyoy']
Sign up to request clarification or add additional context in comments.

Comments

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.