1

Is there a really easy way to save a list of strings to a file in Python? The strings should be separated by new lines, and the file is to be read by humans, outside of Python.

Ideally, something as simple as numpy.savetxt for numeric arrays.

1 Answer 1

1

Using pickle.dump:

with open('/path/to/file', 'wb') as f:
    pickle.dump(a_list_of_strings, f)

To get the list back, use pickle.load.

UPDATE for human readable output, use file.writelines.

Assuming there's no newline is contained in the strings:

with open('/path/to/file', 'w') as f:
    f.writelines('%s\n' % s for s in a_list_of_strings)
Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't work. If I run with open('~/Desktop/test', 'w') as f: pickle.dump(['a','b'], f) the written file contains gibberish: (lp0 S'a' p1 aS'b' p2 a. The file should be human-readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.