Save a list to a .txt file

Question:

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.

Answers:

Try this, if it helps you

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

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

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

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

Answered By: shantanu pathak

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)
Answered By: Farhan Hai Khan

For performance and other purposes, and assuming you will also want to read and write stuff from a file, use json formats!

P.S. – You can write to txts as well, but jsons are a standard for saving such objects!

ORJSON is the goto standard for this task. Also supports nested lists/dicts/other complex structures.

NOTE : ORJSON is faster and more serializable than the inbuilt JSON library but both can perform the same.

import orjson

def pretty_view_dict(normal_dict):
    print(orjson.dumps(normal_dict, option=orjson.OPT_INDENT_2).decode('utf-8'))

def read_json_file(fpath):
    with open(fpath, "r") as f:
        data = orjson.loads(f.read())
    return data

def write_json_file(fpath, data):
    with open(fpath, "wb") as f:
        f.write(orjson.dumps(data, option= orjson.OPT_INDENT_2))
    return True
Answered By: Farhan Hai Khan
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.