Save a list to a .txt file

You can use inbuilt library pickle

This library allows you to save any object in python to a file

This library will maintain the format as well

import pickle
with open('/content/list_1.ob', 'wb') as fp:
    pickle.dump(list_1, fp)

you can also read the list back as an object using same library

with open ('/content/list_1.ob', 'rb') as fp:
    list_1 = pickle.load(fp)

NOTE:: File can have any extension you are comfortable with. These files are binary and are not supposed to be viewed manually.

reference : Writing a list to a file with Python


If you have more then 1 dimension array

with open("file.txt", 'w') as output:
    for row in values:
        output.write(str(row) + '\n')

Code to write without '[' and ']'

with open("file.txt", 'w') as file:
        for row in values:
            s = " ".join(map(str, row))
            file.write(s+'\n')

Try this, if it helps you

values = ['1', '2', '3']

with open("file.txt", "w") as output:
    output.write(str(values))

Tags:

Python

List