Split file into several and reformat

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Jun 21 17:14:22 EDT 2007


En Thu, 21 Jun 2007 02:45:38 -0300, <bomber71 at aapt.net.au> escribió:

> I want to take read an input file (sels.txt) that looks like:
>
> Begin sels
>    sel1 = {1001, 1002, 1003, ...
>            ...
>            1099}
>
>    sel2 = {1001, 1008, 1009 ...
>            ...
>            1299}
> End sels
>
> And turn it into an output file for each of the "sels" in the input  
> file, i.e
> sel1.txt:
>
> L1001
> L1002
> L1003
> ...
> L1099

- You could ignore the begin and end lines; the important delimiters  
appear to be { and }
- Repeat:
   - read lines until you find a {
   - extract whatever is at the left of = as the "sel" name; keep whatever  
is at the right of the { as the first line of data
   - keep reading more lines until you find a }
   - split each of those lines on every "," to get your output items
   - write the output file, you are done with one "sel"
- Keep going until end of input file.

Some tips:

- You can iterate along the lines in a file using
     for line in some_file:
        ....
   but perhaps in this case it may be more convenient to use  
some_file.readline()
- The expression: "x" in line, tests if line contains any "x"
- You will find the string methods useful:  
http://docs.python.org/lib/string-methods.html
   In particular: find, split, strip, partition look promising in this case.

-- 
Gabriel Genellina




More information about the Python-list mailing list