将列表变量写入文件

将列表变量写入文件

本文介绍了将列表变量写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.txt文件,我想清理"脏话,所以我编写了一个程序,可以逐个检查单词列表中的每个位置,以及该单词是否出现在列表中的任何位置可审查单词的列表,它将使用var.remove(arg)将其删除.工作正常,列表很干净,但是不能写入任何文件.

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是清除列表.

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

这将返回此错误:

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

我猜这是因为我试图写一个带有变量或列表的文件,但实际上没有其他选择.列表中有3526个项目.

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?

注意:lists.txt不存在,它是通过写入模式创建的.

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

推荐答案

write写入一个字符串.您不能编写list变量,因为即使对于人类来说,很明显,它应该在单词之间用空格或分号来编写,但对于这种假设,计算机没有空余的手脚,应该提供确切的数据(按字节)要写的内容.

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

  • 对于某些任务,使用str(wordlist)转换列表(将返回类似['hi', 'there']的内容)并编写将可以工作(并允许通过eval方法进行检索),但是考虑到空间的使用,这将是非常昂贵的较长的列表(每个字约增加4个字节),可能会花费更多时间.
  • 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.

这篇关于将列表变量写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 19:27