Home | | Problem Solving and Python Programming | Example Python Programs on Files, Modules, Packages

Problem Solving and Python Programming - Example Python Programs on Files, Modules, Packages | Problem Solving and Python Programming : Files, Modules, Packages

Chapter: Problem Solving and Python Programming : Files, Modules, Packages

Example Python Programs on Files, Modules, Packages

Problem Solving and Python Programming : Files, Modules, Packages - brief important questions and answers and Example Python Programs on Files, Modules, Packages

1. Write a function that copies a file reading and writing up to 50 characters at a time.


def copyFile(oldFile, newFile):

f1 = open(oldFile, "r")

f2 = open(newFile, "w")

while True:

text = f1.read(50)

if text == "":

break

f2.write(text)

f1.close()

f2.close()

return

 

2. (a) Write a program to perform exception handling.


def exists(filename):

try:

f = open(filename)

f.close()

return True

except IOError:

return False

 

2. (b) Write a Python program to handle multiple exceptions.


try:

x= float(raw_input("Your number: "))

inverse = 1.0 / x

except ValueError:

print "You should have given either an int or a float"

except ZeroDivisionError:

print "Infinity"

 

3. Write a python program to count number of lines, words and characters in a text file. def wordCount():


cl=0

cw=0

cc=0

f=open("ex88.txt","r") for line in f:

words=line.split()

cl +=1

cw +=len(words)

cc+=len(line)

print('No. of lines:',cl)

print('No. of words:',cw)

print('No. of characters:',cc)

f.close()

 

4. Write a Python program to illustrate the use of command-line arguments.


import sys

def inputCmd():

print ("Name of the script:", sys.argv[0])

print ("Number of arguments:", len(sys.argv))

print ("The arguments are:", str(sys.argv))

 

5. Mention the commands and their syntax for the following: get current directory, changing directory, list, directories and files, make a new directory, renaming and removing directory.


(a) Get current directory: getcwd()

Syntax : import os

os.getcwd()

(b) Changing directory: chdir()

Syntax: os.chdir(‘C:\\Users’)

os.getcwd()

(c) List directories and files: listdir()

Syntax: os.listdir()

(d) Making a new directory: mkdir()

Syntax: os.mkdir(‘Newdir’)

(e) Renaming a directory: rename()

os.rename(‘Newdir’,’Newname’)

os.listdir()

(f) Removing a directory: remove()

os.remove(‘NewName’)

 

6. Write a Python program to implement stack operations using modules.


Module definition:

def getStack():

return[]

def isempty(s):

if s==[]:

return True

else:

return False

def top(s):

if isempty(s):

return None

else:

return s[len(s)-1]

def push(s,item):

s.append(item)

def pop(s):

if isempty(s):

return None

else:

item=s[len(s)-1]

del s[len(s)-1]

return item

 

Program to call stack :

import stack

def today():

mystack=stack.getStack()

for item in range(1,7):

stack.push(mystack,item)

print('Pushing',item,'to stack')

print ('Stack items')

while not stack.isempty(mystack):

item=stack.pop(mystack)

print('Poping',item,'from stack')

 

7. Write a program to illustrate multiple modules. import wordcount,ex12,ex97


def test():

wordcount.wordCount()

def test2():

ex12.inputNumber()

def test3():

ex97.fun()

 

ex97.py:

def fun():

try:

x= float(raw_input("Your number: "))

inverse = 1.0 / x

except ValueError:

print "You should have given either an int or a float"

except ZeroDivisionError:

print "Infinity"

 

ex12.py:

def inputNumber () :

x = input ('Pick a number: ')

if x == 17 :

raise ValueError, '17 is a bad number'

return x

 

wordcount.py:

def wordCount():

cl=0

cw=0

cc=0

f=open("ex88.txt","r")

for line in f:

words=line.split()

cl +=1

cw +=len(words)

cc+=len(line)

print('No. of lines:',cl)

print('No. of words:',cw)

print('No. of characters:',cc)

f.close()

 

8. Write a Python program to dump objects to a file using pickle. import pickle


def funMap():

cities = ["Chennai", "delhi","Mumbai","Kolkata"]

fh=open("cities.pck","w")

pickle.dump(cities,fh)

fh.close()

f=open("cities.pck","r")

cts=pickle.load(f)

print(cts)


Tags : Problem Solving and Python Programming , Problem Solving and Python Programming : Files, Modules, Packages
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Files, Modules, Packages : Example Python Programs on Files, Modules, Packages | Problem Solving and Python Programming


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.