How to write a list to a file and read a list from file using Python

Many a times we need to store list in a file for later usage, in such cases, its better to store list in a file and read this file into list whenever we need to use. Python has very easy methods for achieving this.

 

################################################################################################
# name: list_to_file_01.py
# desc:
# date: 2019-03-30
# Author: conquistadorjd
################################################################################################
print('*** Program Started ***')
score = ["one","two","three", "four"]
with open("list_to_file.txt", "w") as f_write:
for s in score:
f_write.write(str(s) +",")
with open("list_to_file.txt", "r") as f_read:
lines = f_read.read().split(',')
print('lines : ', lines )
print('type of lines : ', type(lines) )
for line in lines:
print("line : ", line)
print('*** Program Completed ***')

view raw
list_to_file_01.py
hosted with ❤ by GitHub

Output of the program

*** Program Started ***
lines : ['one', 'two', 'three', 'four', '']
type of lines : <class 'list'>
line : one
line : two
line : three
line : four
line :
*** Program Completed ***

file generated is as below

one,two,three,four,

view raw
list_to_file.txt
hosted with ❤ by GitHub

Here is another version of same program

################################################################################################
# name: list_to_file_02.py
# desc:
# date: 2019-03-30
# Author: conquistadorjd
################################################################################################
print('*** Program Started ***')
score = ["one","two","three", "four"]
f_write = open("list_to_file.txt", "w")
for s in score:
f_write.write(str(s) +",")
# Expkicite close is needed in this case
f_write.close()
f_read = open("list_to_file.txt", "r")
lines = f_read.read().split(',')
print('lines : ', lines )
print('type of lines : ', type(lines) )
for line in lines:
print("line : ", line)
## This close can be ommited considering program termination closes all open files.
f_read.close()
print('*** Program Completed ***')

view raw
list_to_file_02.py
hosted with ❤ by GitHub

output and file generated is same except file opening closing styles are different.