将列表列表打印到文件中时,请删除引号和方括号



我的列表看起来像这个

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

我该如何将其存储在文本文件中,使其看起来像这个

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

一旦转换为字符串,我就会在子列表上使用regex。

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")

这为我提供了一个txt文件,看起来就像你想要的输出显示的那样:

1,book1,dffd
2,book2,dsd

为了解释这个过程,子列表被迭代,转换为字符串,然后用regex删除任何不需要的符号,然后将清理后的数据写入txt文件,并在每个子列表的末尾添加一行新行。

最新更新