Write list variable to file

Question:

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.

Asked By: oisinvg

||

Answers:

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.
Answered By: Uriel

If you want a better formatting for structural data you can use built-in json module.

text_file.write(json.dumps(list_data, separators=(',n', ':')))

The list will work as a python variable too. So you can even import this later.

So this could look something like this:

var_name = 'newlist'
with open(path, "r+", encoding='utf-8') as text_file:
  text_file.write(f"{var_name} = [n")
  text_file.write(json.dumps(list_data, separators=(',n', ':')))
  text_file.write("n]n")
Answered By: Nux
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.