Write list variable to file

六月ゝ 毕业季﹏ 提交于 2019-12-12 17:51:07

问题


I have a .txt file of words I want to 'clean' of swear words, so I have written a program which checks each position, one-by-one, of the word list, and if the word appears anywhere within the list of censorable words, it removes it with var.remove(arg). It's worked fine, and the list is clean, but it can't be written to any file.

wordlist is the clean list.

    newlist = open("lists.txt", "w")
    newlist.write(wordlist)
    newlist.close()

This returns this error:

    newlist.write(wordlist)
    TypeError: expected a string or other character buffer object

I'm guessing this is because I'm trying to write to a file with a variable or a list, but there really is no alternate; there are 3526 items in the list.

Any ideas why it can't write to a file with a list variable?

Note: lists.txt does not exist, it is created by the write mode.


回答1:


write writes a string. You can not write a list variable, because, even though to humans it is clear that it should be written with spaces or semicolons between words, computers do not have the free hand for such assumptions, and should be supplied with the exact data (byte wise) that you want to write.

So you need to convert this list to string - explicitly - and then write it into the file. For that goal,

newlist.write('\n'.join(wordlist))

would suffice (and provide a file where every line contains a single word).


  • For certain tasks, converting the list with str(wordlist) (which will return something like ['hi', 'there']) and writing it would work (and allow retrieving via eval methods), but this would be very expensive use of space considering long lists (adds about 4 bytes per word) and would probably take more time.


来源:https://stackoverflow.com/questions/43701610/write-list-variable-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!