Samuel Mideksa
Samuel Mideksa

Reputation: 465

How to convert a file containing a list of lists to a string?

I have a text file with the following content

[['server', ' working'], ['android', ' working'], ['using', ' could']]

From this .txt file I want to ouput another .txt file with content

server, working

android, working

using, cloud

with an empty line between them. I have tried this

        text_file = 'str_arr.txt'
        with open(text_file, 'r') as f:
            myNames = f.readlines()
        output = ""
        for word in myNames:
            for characters in word:
                output += characters +","
            output = output[:-1] + "\n"
        print(output)

And it's output is

[,[,'s','e','r','v','e','r'],..],]

Upvotes: 1

Views: 50

Answers (1)

Jan
Jan

Reputation: 43169

Using ast & join:

from ast import literal_eval

lst = literal_eval("""[['server', ' working'], ['android', ' working'], ['using', ' could']]""")

out = "\n\n".join(
    ", ".join(x for x in sublst)
    for sublst in lst)
print(out)

This yields

server,  working

android,  working

using,  could

For your purpose, you'd need to get the file content as well:

with open("your_file", "r") as fp:
    lst = literal_eval(fp.read())
    # or fp.readlines()
    ...

Upvotes: 2

Related Questions