36

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']

can I save it to a file that contains:

'['1','2','3']'

So far I print parts of the list in the terminal and copy those in to a txt file.

Peter Wood
  • 22,682
  • 5
  • 57
  • 94

4 Answers4

67

Try this, if it helps you

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

with open("file.txt", "w") as output:
    output.write(str(values))
Peter Wood
  • 22,682
  • 5
  • 57
  • 94
Mangu Singh Rajpurohit
  • 9,850
  • 4
  • 59
  • 90
  • How could you then open the txt file please? I write changing "w" with "r" and read_csv too – asd Feb 24 '21 at 17:31
  • 1
    Using json allows the file to actually be readable - https://stackoverflow.com/questions/27745500/how-to-save-a-list-to-a-file-and-read-it-as-a-list-type – Eldwin Mar 18 '21 at 04:47
35

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')
  • +1 this one is the most parse-able way to write a list into a file, the other answer is also correct of course but will give a strange python list format in the output file – FatihSarigol Jul 20 '20 at 14:15
14

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

shantanu pathak
  • 1,806
  • 16
  • 23
  • Aren't pickle files a binary format? I got the impression, from teh .txt extension on the OP's file that he wanted a plain-text file that he could view, say, in a text viewer. Maybe I am wrong about pickle? – Brian Feb 19 '21 at 16:45
  • @Brian .. yes We can't open the pickled file and view it in plain text. .txt may give this feeling. I am editing my answer accordingly. – shantanu pathak Mar 05 '21 at 02:41
0

I use a logger of my own creation :

import json
import timeit
import traceback
import sys
import unidecode

def main_writer(f,argument):
  try:
    f.write(str(argument))
  except UnicodeEncodeError:
    f.write(unidecode.unidecode(argument))


def logger(*argv,logfile="log.txt",singleLine = False):
  """
  Writes Logs to LogFile
  """
  with open(logfile, 'a+') as f:
    for arg in argv:
      if arg == "{}":
        continue
      if type(arg) == dict and len(arg)!=0:
        json_object = json.dumps(arg, indent=4, default=str)
        f.write(str(json_object))
        f.flush()
        """
        for key,val in arg.items():
          f.write(str(key) + " : "+ str(val))
          f.flush()
        """
      elif type(arg) == list and len(arg)!=0:
        for each in arg:
          main_writer(f,each)
          f.write("\n")
          f.flush()
      else:
        main_writer(f,arg)
        f.flush()
      if singleLine==False:
        f.write("\n")
    if singleLine==True:
      f.write("\n")

def tryFunc(func, func_name=None, *args, **kwargs):
  """
  Time for Successfull Runs
  Exception Traceback for Unsuccessful Runs
  """
  stack = traceback.extract_stack()
  filename, codeline, funcName, text = stack[-2]
  func_name = func.__name__ if func_name is None else func_name # sys._getframe().f_code.co_name # func.__name__
  start = timeit.default_timer()
  x = None
  try:
    x = func(*args, **kwargs)
    stop = timeit.default_timer()
    # logger("Time to Run {} : {}".format(func_name, stop - start))
  except Exception as e:
    logger("Exception Occurred for {} :".format(func_name))
    logger("Basic Error Info :",e)
    logger("Full Error TraceBack :")
    # logger(e.message, e.args)
    logger(traceback.format_exc())
  return x

def bad_func():
  return 'a'+ 7

if __name__ == '__main__':
    logger(234)
    logger([1,2,3])
    logger(['a','b','c'])
    logger({'a':7,'b':8,'c':9})
    tryFunc(bad_func)
Farhan Hai Khan
  • 416
  • 6
  • 8