first field criteria to new file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dragrid
    New Member
    • Jan 2009
    • 29

    first field criteria to new file

    need to break out a file into three separate files based on first field e.g.

    file = ['aaa sfsfs sfsdfs sdfes'
    aaa srgfr grg ht hrhr
    aaa egero eriore erore',
    hh dsrgr rger ergerl rr
    hh oefsrf werf ewf wfre,
    k efwgwe wfwer fwe fwetf,
    ddd fsff rgferw grwr
    ddd wfrewe gptrg rer
    ddd eortwer writwer erwo,
    m fwewi qoovsd sjrrs fe ,]

    so go through file and lines where the first three consecutive lines have the same first field send those three lines to file1, lines where only two cosecutive lines have the same first fields send to file 2 and rest which is only 1 unique first field to file 3 - so lines aaa ... and ddd ....would be in file1 etc..etc..

    any idea how to read thru a file and do this is very much appreciated - Thanks
  • kudos
    Recognized Expert New Member
    • Jul 2006
    • 127

    #2
    There is some unclearities here, however I guess the way to go would be the following:

    Code:
    filec = {}
    for f in file:
     key  =""
     for r in range(3):
      key+=f[r]
     if(filec.has_key[key]):
      filec[key]+=f+"\n"
     else:
      filec[key]=f+"\n"
    
    for k in filec.keys():
     f = open(k,"w")
     f.write(filec[k])
     f.close()
    (I haven't had the possiblity to test the code, but it should be something like this)

    -kudos

    Comment

    Working...