Save a list to a .txt file

后端 未结 3 788
不思量自难忘°
不思量自难忘° 2020-12-14 02:11

Is there a function in python that allows us to save a list in a txt file and keep its format?

If I have the list:

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


        
相关标签:
3条回答
  • 2020-12-14 02:49

    Try this, if it helps you

    values = ['1', '2', '3']
    
    with open("file.txt", "w") as output:
        output.write(str(values))
    
    0 讨论(0)
  • 2020-12-14 02:51

    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')
    
    0 讨论(0)
  • 2020-12-14 02:58

    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.txt', '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.txt', 'rb') as fp:
        list_1 = pickle.load(fp)
    

    reference : Writing a list to a file with Python

    0 讨论(0)
提交回复
热议问题