write list in file python code example
Example 1: Python program to write a list to a file
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
with open('file1.txt','w+') as f:
for i in color:
f.write('%s\n'%i)
with open('file1.txt') as f:
print(f.read())
###############
list1=[]
with open('file1.txt','r+') as f:
lines = f.readlines()
for line in lines:
item = line[:-1]
list1.append(item)
print(list1)
#############
with open('file1.txt','r') as f:
lines=f.read()
listli=lines.split('\n')
print(listli)
# listli=lines.strip()
# print(listli)
Example 2: how to save python list to file
import json
a = [1,2,3]
with open('test.txt', 'w') as f:
f.write(json.dumps(a))
#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
a = json.loads(f.read())
Example 3: python write a list to a file line by line
# attempt #1
f = open("Bills.txt", "w")
f.write("\n".join(map(lambda x: str(x), bill_List)))
f.close()
# attempt #2
# Open a file in write mode
f = open('Bills.txt', 'w')
for item in bill_List:
f.write("%s\n" % item)
# Close opend file
f.close()
# attempt #3
with open('Bills.txt', 'w') as f:
for s in bill_List:
f.write(s + '\n')
with open('Bills.txt', 'r') as f:
bill_List = [line.rstrip('\n') for line in f]
# attempt #4
with open('Bills.txt', 'w') as out_file:
out_file.write('\n'.join(
bill_List))
Example 4: how to write lists to text file python
# define list of places
places = ['Berlin', 'Cape Town', 'Sydney', 'Moscow']
with open('listfile.txt', 'w') as filehandle:
for listitem in places:
filehandle.write('%s\n' % listitem)