0

Following up my previous question, because I couldn't get a satisfactory answer. Now I have data like this, don't know what it exactly is

["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]

I'd like my final output to be written to a csv file like below. How can I achieve this?

A        ,B    ,C
a1,a2    ,b1   ,c1
a2,a4    ,b3   ,ct
4
  • I get error when trying to set a value equal to ["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"] do you mean--> ['A','B','C']['a1,a2','b1','c1']['a2,a4','b3','ct'] ? Commented Nov 24, 2014 at 6:49
  • @Jay No. It has both single and double quotes. Commented Nov 24, 2014 at 6:51
  • as a string? like --> "["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]" ? Because you cannot set a variable to that i.e a = ["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"] Commented Nov 24, 2014 at 6:52
  • @Jay It's just the way I posted in the question above. ["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"] I have no idea what it could be. I did mydata = [mydata.replace("|", "")[1:-1]] because I had to replace the "|"'s I had in my data. The entire thing is definitely a string. Commented Nov 24, 2014 at 6:55

3 Answers 3

0

Assuming that ["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"] is one long string as the original post seems to imply, ie:

"""["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]""" 

then the following code should work:

# ORIGINAL STRING
s = """["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]"""

# GET RID OF UNNECESSARY CHARACTERS FOR OUR CSV
s = s.replace("][", "--") # temporary chars to help split into lines later on
s = s.replace("[", "")
s = s.replace("]", "")
s = s.replace("\'", "")
s = s.replace("\"", "")

# SPLIT UP INTO A LIST OF LINES OF TEXT
lines = s.split("--")

# WRITE EACH LINE IN TURN TO A CSV FILE
with open("myFile.csv", mode = "w") as textFile:
    # mode = w     to override any other contents of an existing file, or 
    #              create a new one.
    # mode = a       To append to an exising file
    for line in lines:
      textFile.write(line + str("\n"))
Sign up to request clarification or add additional context in comments.

Comments

0

An alternative way, again assuming that the data is encoded as one long string:

import ast

# ORIGINAL STRING
s = """["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]"""

# PARSE INTO A LIST OF LISTS WITH STRING ELEMENTS
s2 = s.replace("][", "],[")
s2 = ast.literal_eval(s2)
s2 = [ast.literal_eval(s2[x][0]) for x in range(len(s2))]

# WRITE EACH LIST AS A LINE IN THE CSV FILE                     
with open("myFile.csv", mode = "w") as textFile:
        # mode = w     to override any other contents of an existing file, or 
        #              create a new one.
        # mode = a       To append to an exising file
        for i in range(len(s2)):
          line = ",".join(s2[i])
          textFile.write(line + str("\n"))

Comments

0

Since the given input won't be accepted by any inbuilt data structure, you need to convert it either into a string or a list of lists. Assuming your input as a string in the following. Also, you can modify the formatting as per your requirement.

#!/usr/bin/python

from ast import literal_eval

def csv(li):
    file_handle = open("test.csv", "w")
    #stripping the outer double_quotes and splitting the list by commas
    for outer in li:
        temp = outer[0].strip("'")
        temp = temp.split("',")
        value = ""
        #bulding a formatted string(change this as per your requirement
        for inner in temp:
            value += '{0: <10}'.format(inner.strip("'")) + '{0: >10}'.format(",")
        value = value.strip(", ")
        #writing the built string into the file
        file_handle.write(value + "\n")
    file_handle.close()

#assuming your input as string
def main():
    li_str = """["'A','B','C'"]["'a1,a2','b1','c1'"]["'a2,a4','b3','ct'"]"""
    li = []
    start_pos, end_pos = 0, -1
    #break each into a new list and appending it to li
    while(start_pos != -1):
        start_pos = li_str.find("[", end_pos+1)
        if start_pos == -1:
            break
        end_pos = li_str.find("]", start_pos+1)
        li.append(literal_eval(li_str[start_pos:end_pos+1]))
    #li now conatins a list of lists i.e. same as the input
    csv(li)

if __name__=="__main__":
    main()

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.