File Handling
File Handling
Description : When we open a file and we got file object, we can get various details related to that file
by using its properties.
name: Name of opened file
mode: Mode in which the file is opened
closed: Returns boolean value indicates that file is closed or not
readable(): Retruns boolean value indicates that whether file is readable or not
writable(): Returns boolean value indicates that whether file is writable or not.
f=open("Departments.txt",'r')
print("file name :",f.name)
print("file mode :",f.mode)
print("is file readable :",f.readable())
print("is file writable :", f.writable())
print("is file closed :", f.closed)
f.close()
print("is file closed :",f.closed)
Output:
Output:
as occured 3 times
Output:
gnireenignE liviC
level arora madam
e) Write a Python program to compute the number of characters, words and lines in a file.
filename = input("Enter a file name : ")
c = 0
w = 0
l = 0
f1 = open(filename,'w')
f1.write('Computer science Engineering\n')
f1.write('Elecronics and Communication Engineering\n')
f1.write('Civil Engineering\n')
f1.close()
f2 = open(filename,'r')
data = f2.readlines()
print(data)
for i in data:
c = c + len(i)
w = w + len(i.split())
l = l + 1
f2.close()
print('The number of Characters are :', c)
print('The number of Words are :', w)
print('The number of Lines are :', l)
output: