array to CSV

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pepijn
    New Member
    • Aug 2008
    • 2

    array to CSV

    I have multiple txt files which each have a column of 41 numbers. I want to write them as a collective into a CSV file.

    this is what i wrote for 4 of the txt's:

    import csv

    b = 4
    for j in range(0,b):

    log_code = "/users/administrator/desktop/hbridgetest%04d .txt"%(j)

    in_file = open(log_code," r")
    numberof = in_file.readlin es()
    in_file.close()

    # write .csv file for hb data
    wf=csv.writer(f ile('bridge.csv ','wb'),dialect ='excel')
    wf.writerows(nu mberof)

    however,
    i'm just getting the last column in the CSV with the numbers split up (ie. 4156 is 4 1 5 6, each in a different column).

    please help me.
  • pepijn
    New Member
    • Aug 2008
    • 2

    #2
    i've changed it a little bit:

    import csv
    b = 4
    bridge1 = []
    for j in range(0,b):

    log_code = "/users/administrator/desktop/hbridgetest%04d .txt"%(j)

    in_file = open(log_code," r")
    sequences = in_file.read()
    in_file.close()

    sequences = sequences.split ()
    bridge = []
    for k in range(0,40):
    bridge.append(i nt(sequences[k]))
    bridge1.append( bridge)

    # write .csv file for hb data
    wf=csv.writer(f ile('bridge1.cs v','wb'),dialec t='excel')
    wf.writerow(bri dge1)


    made a list of lists and then wrote the lists into the csv. however, i now have a list in A1, B1, C1, D1 within excel. How can i let those lists drop down into the column?

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Let's assume you have a list of file names fn_list. Read each file into a list of lists. Built-in function zip can make rows from each element of the sublists. The following does not use the csv module:
      [code=Python]
      output_list = zip(*[[item.strip() for item in open(fn).readli nes()] for fn in fn_list])
      output = '\n'.join([','.join(sublis t) for sublist in output_list])
      f = open('numbers_c ombined.csv', 'w')
      f.write(output)
      f.close()[/code]
      Sample output string:
      Code:
      >>> output
      '155342,23,8976\n3774723,477,89998\n36643,6996,4884\n27,586858,858\n34005,298894887,89488\n2006,12,75567'
      >>> print output
      155342,23,8976
      3774723,477,89998
      36643,6996,4884
      27,586858,858
      34005,298894887,89488
      2006,12,75567
      >>>

      BTW - Please use code tags around your code. It is impossible to follow indentations otherwise.

      Comment

      Working...