Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You just have a function which parses one file, and returns a list of dictionaries containing <code>{'name': 'Bob Simon', 'age': 29, ...}</code> etc. Then call this on each of your files, extending a master list. Then write this master list of dicts as a CSV file.</p> <p>More elaborately:</p> <p>First you need to parse the input files, you'd have a function which takes a file, and returns a list of "things".</p> <pre><code>def parse_txt(fname): f = open(fname) people = [] # Here, parse f. Maybe using a while loop, and calling # f.readline() until there is an empty line Construct a # dictionary from each person's block, and append it to allpeople return people </code></pre> <p>This returns something like:</p> <pre><code>people = [ {'name': 'Bob Simon', 'age': 29}, {'name': 'Susan Kim', 'age': 21}, ] </code></pre> <p>Then, loop over each of your input files (maybe by using <code>os.listdir</code>, or <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> to get a list of args):</p> <pre><code>allpeople = [] for curfile in args: people = parse_txt(fname = curfile) allpeople.extend(people) </code></pre> <p>So <code>allpeople</code> is a long list of all the people from all files.</p> <p>Finally you can write this to a CSV file using the <a href="http://docs.python.org/library/csv.html#csv.writer" rel="nofollow">csv module</a> (this bit usually involves another function to reorganise the data into a format more compatible with the writer module)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload