54.Example Programs using Files
Write Python code for the following statements ( University question)
i)writes the text ”PROGRAMMING IN PYTHON” to a file with name code.txt
ii) then reads the text again and prints it to the screen.
f=open('code.txt','w')
f.write("PROGRAMMING IN PYTHON")
f.close()
f=open('code.txt','r')
s=f.read()
print(s)
f.close()
Copy file1.dat to file2.dat
try:f1 = open("sample.dat", "r")
f2 = open("sample3.dat", "w")
content=f1.read()
f2.write(content)
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
#copying a binary file ( image)
try:
f1 = open("cat.jpg", "rb")
f2 = open("catcopy.jpg", "wb")
content=f1.read()
f2.write(content)
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
f1 = open("file1.dat", "r")
f2 = open("file2.dat", "w")
while True:
l=f1.readline()
if l=="":
break
f2.write(l)
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
Copy file1.dat to file2.dat after removing blank linesRead a file and writes out a file with the lines in reversed order.We can also do the above program by reversing the file object
Read and print a file with all punctuation removed.( university question)Read a text file and print each word and its length in sorted order
Write a python program to create a file with 10 integer numbers. Read this file and display the square of each number. ( university question)
f1 = open("cat.jpg", "rb")
f2 = open("catcopy.jpg", "wb")
content=f1.read()
f2.write(content)
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
#copying line by line
try:f1 = open("file1.dat", "r")
f2 = open("file2.dat", "w")
while True:
l=f1.readline()
if l=="":
break
f2.write(l)
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
copy file1.dat to file2.dat after removing lines starting with # (comment lines in python)
try:
f1 = open("file1.dat", "r")
f2 = open("file2.dat", "w")
while True:
l=f1.readline()
if l=="":
break
if l[0]!='#':
f2.write(l)
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
try:
f1 = open("file1.dat", "r")
f2 = open("file2.dat", "w")
lst=f1.readlines() # reading lines to a list
for l in lst:
if l !='\n':
f2.write(l)
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
try:
f1 = open("file1.dat", "r")
f2 = open("file2.dat", "w")
lst=f1.readlines() # read the entire contents into a list
rlst=reversed(lst) #reversing the list
f2.writelines(rlst) # writing each line in the new file
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
try:
f1 = open("file1.dat", "r")
f2 = open("file2.dat", "w")
rf1=reversed(list(f1)) # reversing the file object after converting it into a list sequence
for line in rf1:
f2.write(line) # writing each line in the new file
f1.close()
f2.close()
print('File is copied')
except:
print("file does not exist")
import string
intab = string.punctuation
print(intab)
outtab = " "*len(intab)
trantab = str.maketrans(intab, outtab)
try:
f1 = open("file1.dat", "r")
print('File Contents after removing punctuation')
for line in f1: # read each line
print(line.translate(trantab)) #translate punctuations to None
f1.close()
except:
print("file does not exist")
try:
f = open("file1.dat", "r")
s=f.read() #reading the file contents into a string
s=s.replace("\n"," ") #replace all newline with spaces
words=s.split(" ") #split the string into words
words.sort()
print("words and length")
for w in words:
if len(w)!=0:
print (w,len(w))
f.close()
except:
print("file does not exist")
Input n numbers and store the cube of each number in a file
f=open("cube.dat","w")
n=int(input("Enter n.."))
print("Enter ",n ," numbers")
for i in range(0,n):
x=int(input())
x=x**3
f.write(str(x)+"\n")
f.close()
print("file cube.dat is created with cube of numbers")
Create a file with 10 integer numbers and finding the average of odd numbers
#writing 10 numbers into a file
f=open("num.dat","w")
print("Enter 10 integers..")
for i in range(10):
n=input()# note the input is string
f.write(n+"\n") # writing numbers line by line
f.close()
#reading numbers and finding average of odd numbers
f=open("num.dat","r")
s=0
c=0
for n in f:
num=int(n) #converting string n to int num
if num%2 !=0:
s=s+num # finding sum of odd numbers
c=c+1 # finding the count of odd numbers
print("the sum of odd numbers=",s,"count=",c,"average=",s/c)
f.close()
Write a program to read numbers stored in one file and store the sorted
numbers in another file after deleting duplicates.(university question)
try:
f1=open("file1.dat","r") # numbers are stored line by line
lst=f1.readlines() # read the numbers into a list
nlst=list(set(lst)) # removing duplicates easy method is to make a set
nlst.sort() # sorting the list
f2=open("file2.dat","w") #writing into a new file
f2.writelines(nlst)
f1.close()
f2.close()
print("sorted file file2.dat is created")
except:
print("File not found..")
Printing and Finding the count of four letter words in a file ( University Question)
try:
f=open("data.txt","r")
st=f.read()
stn=st.replace("\n"," ")
words=stn.split(" ")
c=0
for w in words:
if len(w)==4:
print(w)
c=c+1
print("Count of 4 letter words=",c)
f.close()
except:
print("File not found..")
#writing 10 numbers into a file
f=open("num.dat","w")
print("Enter 10 integers..")
for i in range(10):
n=input()# note the input is string
f.write(n+"\n") # writing numbers line by line
f.close()
#reading numbers and finding squares of numbers
f=open("num.dat","r")
print("numbers and its squares..")
for n in f:
num=int(n) #converting string n to int num
print(num,num*num)
f.close()
Reading numbers from a file and storing even and odd numbers in two separate files
try:
f1=open("file1.dat","r")
f2=open("odd.dat","w")
f3=open("even.dat","w")
l=f1.readlines()
for i in l:
n=int(i)
if n%2==0:
f3.write(i)
else:
f2.write(i)
f1.close()
f2.close()
f3.close()
print('Files are created...odd.dat-odd numbers even.dat-even numbers')
except:
print("cant find file..")
Reading numbers from a file and storing positive and negative numbers in two separate files
( university question)
try:
f1=open("num.txt","r") # numbers are stored line by line
lst=f1.readlines() # read the numbers into a list
p=[]
n=[]
for i in lst: # seperating postive and negative numbers
if int(i)<0:
n.append(i)
else:
p.append(i)
f2=open("positive.txt","w") #writing into a new files
f3=open("negative.txt","w")
f2.writelines(p)
f3.writelines(n)
f1.close()
f2.close()
f3.close()
print("Files created positive.txt and negative.txt")
except:
print("cant find the input file..")
Print prime numbers from a set of numbers stored in a file
def primetest(n):
prime=True
i=2
while i<=n/2:
if n%i==0:
prime=False
break
i=i+1
return prime
try:
pf=open("numb.dat","r")
while True:
n=pf.readline()
if n=="":
break
n=int(n)
if primetest(n):
print(n)
pf.close()
except:
print("cant find the input file..")
Assume that there is a text file named “numbers.txt”. Write a python program to find the median of list of numbers in the file without using standard function for median ( University Question)
f1=open("numbers.txt","r") # numbers are stored line by line
lst=f1.readlines() # read the numbers into a list
lst.sort()
if len(lst)%2==0:
med=(int(lst[len(lst)//2])+int(lst[len(lst)//2+1]))/2
else:
med=int(lst[len(lst)//2])
print("median=",med)
Write a Python program to store lines of text into a file.Read the file and display only the palindrome words in the file.(university question)
#creating file
f=open("file.data","w")
while True:
ln=input("Enter a line of text...type quit to exit\n")
if ln=='quit':
break
f.write(ln+'\n')
#file contents
f.close()
f=open("file.data","r")
print("file contents...")
for i in f:
print(i,end="")
f.close()
#reading and printing palindrome words
f=open("file.data","r")
lst=f.read()
lst=lst.replace("\n"," ")
words=lst.split(" ")
print("Palindrome words")
for w in words:
if w==w[::-1]:
print(w)
f.close()
Write a Python program to create a text file. Read the contents of the file, encrypt every character in the file with a distance of 3 and write it to a new file.
#Eg:yak is encrypted as bdn.( university question)
try:
f=open("text.dat","r")
alpha="abcdefghijklmnopqrstuvwxyz"
ns=""
s=f.read()
for c in s:
if c in alpha:
c=ord(c)+3
if c > 122:
c=c-26
c=chr(c)
ns=ns+c
nf=open("textnw.dat","w")
nf.write(ns)
f.close()
nf.close()
print("FILE ENCRYPTED...and stored in textnw.dat")
except:
printf("cant find the file..")
Replace all string pyton with python in a file
#input file fin = open("data.txt", "rt")
#output file to write the result to
fout = open("out.txt", "wt")
#for each line in the input file
for line in fin:
#read replace the string and write to output file
fout.write(line.replace('pyton', 'python'))
#close input and output files
fin.close()
fout.close()
Reading last 5 characters from a file
Note: for the negative offset in seek , file must be opened in binary(b) mode.
f=open("test.dat","w")
l=['mec\n','thrikakara\n','cochin']
f.writelines(l)
f.close()
f=open("test.dat","rb")
f.seek(-6,2)
print(f.read(6).decode('utf-8'))
f.close()
Print the last three lines of a file
f=open("test.dat","w")
l=['mec\n','thrikakara\n','cochin\n','python\n','programming\n','ktu\n']
f.writelines(l)
f.close()
f=open("test.dat","r")
list=f.readlines()
for l in list[-3:]:
print(l)
f.close()
Comments
Post a Comment