Saturday, July 11, 2020

Python Text File Writing Based Program Based on Sumita Arora Text Book


1. Reading lines from one file and write into another file starting from 's'

r=open('read.txt',"r")  # open file in read mode
w=open("write.txt",'w') # open file in write mode
lines=r.readlines()
for line in lines:
    if(line[0]=='s'):    # write all lines start from 's' from read.txt to write.txt
        w.write(line)
r.close()
w.close()

2. Write first and last line of one file into another file

r=open('read.txt',"r")  # open file in read mode
w=open("write.txt",'w') # open file in write mode
lines=r.readlines()
w.write(lines[0])   # write  first line 
w.write(lines[-1])    # write  last line 
r.close()
w.close()

3. Write lines of one file into anther in reverse form

r=open('read.txt',"r")
w=open("write.txt",'w')
lines=r.readlines()
for line in lines:
    w.write(line[::-1])  # write line in reverse form

r.close()

w.close()

contents of read.txt
my name is mukesh

pgt computer Science

Contents of write.txt file
hsekum si eman ym

ecneicS retupmoc tgp
4. Write only digits from one file to another
fr=open('read.txt',"r")
fw=open("write.txt",'w')
s=fr.read()
w=s.split()
for i in w:
    for c in i:
                  if c.isdigit():  # check  character for digit
                                fw.write(c)
fr.close()
fw.close()

Contents in read.txt
pin code 160014
Mobile no 9646648307
E=mail id: mk168in@gmail.com

Contents in write.txt file
1600149646648307168


5.Writing upper,lower case characters and other  characters input by keyboard in different  files
f1=open('lower.txt',"w")
f2=open('upper.txt',"w")
f3=open('other.txt',"w")
n=int(input("How many characters you want to enter "))
for i in range(n):
      ch=input("Enter a character")
      if ch.islower():
          f1.write(ch)
      elif ch.isupper():
          f2.write(ch)
      else:
          f3.write(ch)
f1.close()
f2.close()
f3.close()


No comments:

Post a Comment