Python Class On Files
Python Class On Files
3. Close the file by calling the close() method on the File object
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is
the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the
file.
w Opens a file for writing only. Overwrites the file if exists. If the file does not exist, creates
a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if exists. If the file
does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That
is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.
#sample program to open a file in read mode
kt=open('E:/text.txt','r')
s=kt.read()
print(s)
readline() function
>>> kt.readline()
>>> kt.readline()
>>> kt.readline()
'this is hussain'
>>> kt=open('E:/text.txt','r')
>>> kt.readline(4)
'this'
Readlines()
>>> kt=open('E:/text.txt','r')
>>> kt.readline()
>>> kt.readlines()
Writing to Files
Python allows to write content to a file in a way similar to how the print() function
“writes” strings to the screen
kt=open('E:/text.txt','w')
kt.write(n)
kt.close()
kt=open('E:/text.txt','r')
print(kt.read())
#sample program to write a file in append mode
kt=open('E:/text.txt','a')
kt.write(n)
kt.close()
kt=open('E:/text.txt','r')
print(kt.read())
#Sample program to write names to a file until python is entered
kt=open('E:/text.txt','a')
while True:
if(n=='python'):
kt.write(n)
break
else:
kt.write(n+'\n')
kt.close()
kt=open('E:/text.txt','r')
print(kt.read())
The file Object Attributes
Attribute Description
kt=open('E:/text.txt','r')
>>> kt.mode
'r'
>>> kt.name
'E:/text.txt'
>>> kt.closed
False
Cursor Positions
Similarly, the tell() method returns our current position (in number of bytes).
>>> kt.tell()
>>> kt.seek(11)
11
>>> kt.read()
'onscript\nsql\npython\njava\npython'
# Read data from a file line by line and print number of lines
fr = open('d:\\myfold\\example2.txt', 'r')
n=0
while True:
line = fr.readline()
if not line:
break
else:
n = n+1
kt=open('E:/sai.txt','r')
n=input('enter the string to search ')
count=0
for i in kt:
if n in i:
print('the string exixts in', count,'line')
else:
count+=1
#To merge contents of two files into third file
k=open('E:/yamuna.txt','r')
kt=open('E:/yamuna1.txt','r')
kt1=open('E:/third.txt','a+')
s=kt.read()
ls=k.readlines()
for i in ls:
st=i[:len(i)-1]+' '+s
kt1.write(st+'\n')
kt1.close()
kt1=open('E:/third.txt','r')
print(kt1.read())
OS Operations:
Python os module provides methods that help you perform file-processing operations,
such as
1) rename() Method
2) remove() Method
Syntax: os.remove(file_name)
The os module has several methods that help you create, remove, and change
directories or Folders.
>>>os.chdir('E:/Python34')
4) The rmdir() method deletes the directory, which is passed as an argument in the method.
Calling os.listdir(path) will return a list of filename strings for each file and folders in the path
argument.
k=os.listdir('E:/sai')
for i in k:
d=os.path.getsize('E:/sai/'+i)
if(d>1024):
k=os.listdir('E:/sai')
for i in k:
if(i.endswith('.py')):
print(i)
Second Method: if we would want to display all python files in subfolders as well
import os
for i in file:
if(i.endswith('.py')):
print(i)
Third Method:
import os
k=list(os.walk('C:/Users/ueser/Desktop/iglobal'))
for i in k:
for j in i:
if(type(j)==list):
for l in j:
if(l.endswith('.txt') or l.endswith('.py')):
print('Size of',l,'is',os.path.getsize('C:/Users/ueser/Desktop/'+f+'/'+l))
else:
p=j.split('/')
f=p[len(p)-1]
Fourth Method
import os
k=list(os.walk('C:/Users/ueser/Desktop/teja'))
for i in k:
p=i[2]
for j in p:
if j.endswith('.py'):
k.write(s)
k=open('E:/navya.txt','w')
k.write(ls)
s=str(ls)
k.write(s)
k.close()
k=open('C:/Users/ueser/Desktop/navya.txt','r')
m=(k.readline()).split(',')
for i in m:
if(i.isalnum()):
print(i)
else:
sc=' !@#$%^&*()-[]'
cch=''
for j in i:
if j not in sc:
cch=cch+j
print(cch)
Second Method:
import re
reobj=re.compile('[0123456789]')
k=open('C:/Users/ueser/Desktop/first.txt','r')
l=(k.read()).split(',')
for i in l:
res=reobj.search(i)
print(res.group())
Checking Path Validity
Calling os.path.exists(path) will return True if the file or folder referred to in the argument
exists and will return False if it does not exist.
Calling os.path.isfile(path) will return True if the path argument exists and is a file and will
return False otherwise.
Calling os.path.isdir(path) will return True if the path argument exists and is a folder and will
return False otherwise
>>> s=open('pythonfiles.txt','r')
>>> os.path.exists('E:/manjeet.txt')
False
>>> os.path.isfile('E:/sai')
False
>>> os.path.isfile('E:/sai/ssl.py')
True
>>> os.path.isdir('E:/sai')
True
>>> os.unlink('E:/sai/ssl.py')
Shutil Module:
Copying Files and Folders
The shutil module provides functions for copying files, as well as entire folders.
shutil.copy(source, destination) will copy the file at the path source to the folder at the path
destination.
shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and every
subfolder and files contained in it (copytree cannot work on existing folders)
For cut and paste we use :
shutil.move(source, destination)
Shelve Module
import shelve
sobj = shelve.open('mys')
sobj.close()
fobj = open('mys.dat')
print(fobj.read())
type(sobj)
<class 'shelve.DbfilenameShelf'>