You are on page 1of 19

Files Reading and Writing:

There are three steps to read or write to files in Python.

1. Call the open() function to return a File object.

2. Call the read() or write() method on the File object.

3. Close the file by calling the close() method on the File object

Different modes of opening a file −

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()

'this is pythonin iglobal\n'

>>> kt.readline()

'sai teaches in iglobal\n'

>>> kt.readline()

'this is hussain'

>>> kt=open('E:/text.txt','r')

>>> kt.readline(4)

'this'
Readlines()

>>> kt=open('E:/text.txt','r')

>>> kt.readline()

'this is pythonin iglobal\n'

>>> kt.readlines()

['sai teaches in iglobal\n', 'this is hussain']

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

#sample program to write a file in write mode

kt=open('E:/text.txt','w')

n=input('enter the value of n ')

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')

n=input('enter the value of n ')

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:

n=input('enter the value of n ')

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

file.closed Returns true if file is closed, false otherwise.

file.mode Returns access mode with which file was opened.

file.name Returns name of the file.

kt=open('E:/text.txt','r')

>>> kt.mode

'r'

>>> kt.name

'E:/text.txt'

>>> kt.closed

False

Cursor Positions

Change current file cursor (position) using the seek() method.

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

print(' Line ', n , ' = ', line)

print(' Number of Lines are ', n)

# Search for a string in a file and print in which line it exists

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

Syntax: os.rename(current_file_name, new_file_name)

2) remove() Method

Syntax: os.remove(file_name)

The os module has several methods that help you create, remove, and change
directories or Folders.

1) mkdir() method of the os module to create directories in the current directory.


>>> os.mkdir('C:/Users/ueser/Desktop/rajesh')
2) getcwd() method displays the current working directory.
>>> os.getcwd()
'C:\\Python34'

3) chdir() method to change the current directory.

>>>os.chdir('E:/Python34')

Use '/' to go to parent drive

4) The rmdir() method deletes the directory, which is passed as an argument in the method.

>>> os.rmdir('E:/test') removes the directory test from E drive

File Sizes and Folder Contents


Calling os.path.getsize(path) will return the size in bytes of the file in the path argument.

Calling os.listdir(path) will return a list of filename strings for each file and folders in the path
argument.

Walking a Directory Tree


Syntax: os.walk(path)

#program to display list of file names and sizes


import os

k=os.listdir('E:/sai')

for i in k:

d=os.path.getsize('E:/sai/'+i)

if(d>1024):

print('File name is',i,'size is',round((d/1024)),'kb')


#display file names with .py extension
First Method
import os

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 fol,sfol,file in os.walk('C:/Python34'):

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'):

print('the size of',j,'is',os.path.getsize(i[0]+'/'+j),'bytes')


#Program to write a list on to a file
If we try to write list to a file following error occurs:

Traceback (most recent call last):

File "C:/Python34/files3456.py", line 4, in <module>

k.write(s)

TypeError: must be str, not list

#program to wrtite list to a file

k=open('E:/navya.txt','w')

k.write(ls)

s=str(ls)

k.write(s)

k.close()

#program to read a data which is a string of list

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

Calling os.unlink(path) will delete the file or folder at that path.

>>> 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')

ls = ['python', 'java', 'c++'] # Ls is list variable

sobj['langs'] = ls # storing ls variable in sobj

sobj.close()

fobj = open('mys.dat')

print(fobj.read())

type(sobj)

<class 'shelve.DbfilenameShelf'>

You might also like