Home > front end >  python - remove quotes and brackets when printing a list of lists into a file
python - remove quotes and brackets when printing a list of lists into a file

Time:12-17

my list looks like this

[['1', 'book1', 'dffd'], ['2', 'book2', 'dsd']]

How would i store it in a text file so it looks like this

1,book1,dffd
2,book2,dsd
textfile = open("books2.txt", "w")
for element in booksdata:
    textfile.write (str(element))
textfile.close()

CodePudding user response:

I would use regex on the sublists once converted to string.

with open("text.txt", "w") as f:
    for item in test:
        str_item = str(item)
        str_item_cleaned = re.sub(r"[[\[\]\'\" ]","",str_item)
        f.write(str_item_cleaned   "\n")

This has provided me with a txt file that looks as your intended output shows:

1,book1,dffd
2,book2,dsd

To explain the process, the sublists are being iterated through, converted to strings, then any of the undesired symbols are being removed with regex, and then that cleaned up data is being written to the txt file along with a new line at the end for each sublist.

CodePudding user response:

ShadowRanger is right. Didn't remove the brackets so revising a bit here:

list = [['1', 'book1', 'dffd'], ['2', 'book2', 'dsd']]

for a in list:
    print(a[0]   ','   a[1]   ','   a[2])

1,book1,dffd
2,book2,dsd
  • Related