【问题标题】:How to remove the stuff lists add when writing to textfiles如何删除写入文本文件时添加的东西列表
【发布时间】:2018-04-15 09:13:02
【问题描述】:

我需要将列表写入名为accounts.txt 的文本文件,格式如下:

kieranc,conyers,asdsd,pop
ethand,day,sadads,dubstep

但是,它以括号结尾:

['kieranc', 'conyers', 'asdsd', 'pop\n']['ethand', 'day', 'sadads', 'dubstep']

这是我的代码(accreplace 是一个列表):

accreplace = [['kieranc', 'conyers', 'asdsd', 'pop\n'],['ethand', 'day', 'sadads', 'dubstep']]
acc = open("accounts.txt", "w") 
for x in accreplace: 
    acc.write(str(x))

【问题讨论】:

  • 请编辑您的问题,并将您的代码和文件作为纯文本而不是图像。
  • 是的,并且确实使用代码块功能,以区分代码和散文。
  • accreplace 长什么样子?

标签: python list


【解决方案1】:

由于accreplace 中的每个元素都是一个列表,str(x) 没有帮助。它只是在它周围添加引号。要以正确的格式打印列表,请使用以下代码:

for x in accreplace:
    acc.write(",".join([str(l) for l in x]))

这会将列表项转换为字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 2020-04-20
    • 2016-02-25
    • 2011-09-20
    • 1970-01-01
    相关资源
    最近更新 更多