In: Computer Science
demonstrate how to write a file named "hcsi 112.txt" while handling exceptions, the sentence given below into separate lines(i.e. each sentence begins from where the comma starts) "how are you today?, my name is Python, am easy to use, simple to write, and object oriented". Also show how to read the lines and store into a list.
#prompt user for entering string
s=input('Enter String seperated by comma:')
li=[]
li=s.split(",") # sentences are seperated by comma and stored in a list
try:
f=open('hcsi 112.txt','w') #open the required file to write lines
for line in li:
f.write(line) # writing each line
f.write("\n")#when comma encounter then next sentence will write in new line
f.close()
except IOError:
print('Enter correct file name')
# reading lines and displaying line by line
f1=open('hcsi 112.txt','r')
text=f1.read()
print(text)
# read lines and store it in a list
lineList = [line.rstrip('\n') for line in open('hcsi 112.txt')]
print(lineList)
OUTPUT