python read lines from list code example
Example 1: Write a Python program to read a file line by line and store it into a list.
def conftolist(fname,mode='r+'):
with open(fname) as f:
lines = [line.strip() for line in f]
print(lines)
conftolist('file1.txt')
############
with open('file1.txt','r+') as f:
# li = list(f)
# print(li)
ls=[]
for l in f:
ls.append(l.strip())
print(ls)
Example 2: python read each line into a list
with open(filename) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]