0% found this document useful (0 votes)
27 views14 pages

Imp 2ia

The document provides a comprehensive overview of Python programming concepts, including file operations, path specifications, and string methods. It explains various methods such as getcwd(), chdir(), and listdir(), along with file reading and writing processes. Additionally, it covers dictionary methods, ZIP file handling, and string manipulation techniques with examples.

Uploaded by

Bharath Bharath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views14 pages

Imp 2ia

The document provides a comprehensive overview of Python programming concepts, including file operations, path specifications, and string methods. It explains various methods such as getcwd(), chdir(), and listdir(), along with file reading and writing processes. Additionally, it covers dictionary methods, ZIP file handling, and string manipulation techniques with examples.

Uploaded by

Bharath Bharath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

IMPORTANT QUESTION AND ANSWERS FOR 2ND IA

Introduction to Python Programmin(BPCLK205B)

Explain the following methods with example i) getcwd() ii) chdir() iii) listdir()
i) getcwd():
• Every program that runs on your computer has a current working directory, or cwd.
• Any filenames or paths that do not begin with the root folder are assumed to be under the current working
directory.
• the current working directory as a string value can be obtained with the os.getcwd() function
eg: >>> import os
>>> os.getcwd()
'C:\\Python34'
ii) chdir():
• to change the current working directory the function that can be used is chdir().
Eg:
>>> os.chdir('C:\\Windows\\System32')
>>> os.getcwd()
'C:\\Windows\\System32'
iii) listdir():Calling os.listdir(path) will return a list of filename strings for each file in the path argument.
Eg:
>>> os.listdir('C:\\Windows\\System32')
['0409', '12520437.cpx', '12520850.cpx', '5U877.ax','aaclient.dll',
'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']

Explain Absolute Path and Relative Path. How to specify Absolute Path and Relative Path?

• There are two ways to specify a file path.


• An absolute path, which always begins with the root folder
• A relative path, which is relative to the program’s current working directory.
• There are also the dot (.) and dot-dot (..) folders.
• A single period (“dot”) for a folder name is shorthand for “this directory.”
• Two periods (“dot-dot”) means “the parent folder.”

1
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

Explain file reading and file writing process with an example.


• There are three steps to reading or writing 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.
Opening Files with the open() Function
• helloFile = open('C:\\Users\\your_home_folder\\hello.txt')
Reading the Contents of Files:
• If we want to read the entire contents of a file as a string value, use the File object’s read() method.
Eg:

>>> helloContent = helloFile.read()


>>> helloContent
• the readlines() method can also be used to get a list of string values from the file, one string for each line of text.

Writing to Files:
Write mode will overwrite the existing file and start from scratch, just like when you overwrite a variable’s value
with a new value. Pass 'w' as the second argument to open() to open the file in write mode. Append mode, on the
other hand, will append text to the end of the existing file. Passing 'a' as the second argument to open() opens the
file in append mode.
>>> baconFile = open('bacon.txt', 'w')
>>> baconFile.write('Hello world!\n')
13

Explain the following file operations in python with example


i) Copying Files and folders ii) Moving Files and folders
iii) Permanently deleting files and folders iv) safe delete v) walking a directory tree
i) Copying Files and folders:
• Calling shutil.copy(source, destination) will copy the file at the path source to the folder at the path
destination. (Both source and destination are strings.) If destination is a filename, it will be used as the
new name of the copied file. This function returns a string of the path of the copied file.
>>> import shutil, os
>>> os.chdir('C:\\')
>>> shutil.copy('C:\\spam.txt', 'C:\\delicious')
Output: 'C:\\delicious\\spam.txt'
• The shutil.copy() call copies the file at C:\spam.txt to the folder C:\delicious. The return value is the path
of the newly copied file.
>>> shutil.copy('eggs.txt','C:\\delicious\\eggs2.txt')
Output: 'C:\\delicious\\eggs2.txt'

2
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

ii) Moving Files and folders:


• Calling shutil.move(source, destination) will move the file or folder at the path source to the path destination and
will return a string of the absolute path of the new location.
• If destination points to a folder, the source file gets moved into destination and keeps its current filename.
>>> import shutil
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
Output: 'C:\\eggs\\bacon.txt'
• If there had been a bacon.txt file already in C:\eggs, it would have been overwritten. Since it’s easy to accidentally
overwrite files in this way, you should take some care when using move().
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt')
Output: 'C:\\eggs\\new_bacon.txt'
iii) Permanently deleting files and directory
We can delete a single file or a single empty folder with functions in the os module, whereas to delete a folder and
all of its contents, you use the shutil module.
• Calling os.unlink(path) will delete the file at path.
• Calling os.rmdir(path) will delete the folder at path. This folder must be empty of any files or folders.
• Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will also be deleted.
Eg:
import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)
iv) Safe delete
Using send2trash is much safer than Python’s regular delete functions, because it will send folders and files to your
computer’s trash or recycle bin instead of permanently deleting them.
import send2trash
>>> baconFile = open('bacon.txt', 'a') # creates the file
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt')
v) walking a directory tree
• we can walk through the directory tree, touching each file by using the os.walk() function.
• The os.walk() function is passed a single string value: the path of a folder.
• We can use os.walk() in a for loop statement to walk a directory tree.
• Unlike range(), the os.walk() function will return three values on each iteration through the loop: 1. A string of the
current folder’s name 2. A list of strings of the folders in the current folder 3. A list of strings of the files in the
current folder.
Eg:
import os
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
print('The current folder is ' + folderName)
for subfolder in subfolders:

3
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

print('SUBFOLDER OF ' + folderName + ': ' + subfolder)


for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print(''”)
What is meant by Compressing files? Explain reading, extracting and creating Zip files with code snippet.
• ZIP files (with the .zip file extension), which can hold the compressed contents of many other files. Compressing
a file reduces its size, which is useful when transferring it over the Internet.
• ZIP file can also contain multiple files and subfolders, it’s a handy way to package several files into one. This
single file, called an archive file.
Reading ZIP Files
• To read the contents of a ZIP file, first you must create a ZipFile object (note the capital letters Z and F).
• ZipFile objects are conceptually similar to the File objects you saw returned by the open() function.
• They are values through which the program interacts with the file.
• To create a ZipFile object, call the zipfile.ZipFile() function, passing it a string of the .zip file’s filename.
• Note that zipfile is the name of the Python module, and ZipFile() is the name of the function.
Eg:
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.namelist()
['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']
>>> spamInfo = exampleZip.getinfo('spam.txt')
>>> spamInfo.file_size
13908
>>> spamInfo.compress_size
3828
>>> 'Compressed file is %sx smaller!' % (round(spamInfo.file_size / spamInfo.compress_size, 2))
'Compressed file is 3.63x smaller!'
>>> exampleZip.close()
Extracting from ZIP Files
• The extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the current working
directory.
Eg:
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.extractall()
>>> exampleZip.close()
Define Dictionary. Discuss items(), keys(), values(),get(), and setdefault() dictionary methods in Python with
examples
• A dictionary is a collection of many values.
• Indexes for dictionaries are called keys, and a key with its associated value is called a key-value pair.
• A dictionary is typed with braces, {}.
• Dictionary items are ordered, changeable, and does not allow duplicates.
thisdict{ ={
"brand": "Ford",

4
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

"model": "Mustang",
"year": 1964
}
items():
The values in the dict items value returned by the items() method are tuples of the key and value.
dict = {'color': 'red', 'age': 42}
for i in dict.items():
print(i)
('color', 'red')
('age', 42)

keys():
if we want to access only the keys of the dictionary items, then keys() function is used.
for k in dict.keys():
print(k)
color
age

values():
The values in the dict items are returned by the values () method.
dict = {'color': 'red', 'age': 42}
for v in dict.values():
print(v)
red
42

get() Method
• To check whether a key exists in a dictionary before accessing that key‟s value.
• dictionaries have a get() method that takes two arguments: the key of the value to retrieve and a fallback value to
return if that key does not exist.
items = {'apples': 5, 'cups': 2}
'I am bringing ' + str(items.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
'I am bringing ' + str(items.get('eggs', 0))+ ' eggs.'
'I am bringing 0 eggs.'

setdefault() Method
• The setdefault() method has 2 arrguments. The first argument passed to the method is the key to check for,
and the second argument is the value to set at that key if the key does not exist. If the key does exist, the
setdefault() method returns the key‟s value.
dict = {'name': 'Pooka', 'age': 5}
dict.setdefault('color', 'black')
output='black'

dict= {'color': 'black', 'age': 5, 'name': 'Pooka'}


dict.setdefault('color', 'white')
output='black'

Explain the various string methods for the following operations with examples.

5
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

(i) Removing whitespace characters from the beginning, end or both sides of a string.
(ii) To right-justify, left-justify, and center a string
(iii) join() and split()
(iv) isalpha(),isdecimal(),isalnum()
(v) startswith() and endswith()
• The strip() string method will return a new string without any whitespace characters at the beginning or end.
• The lstrip() and rstrip() methods will remove whitespace characters from the left and right ends, respectively.

txt = “ hello world “


txt.strip()
output= “hello world”
txt.lstrip()
output= “hello world”
txt.rstrip()
output=” hello world”

• Optionally, a string argument will specify which characters on the ends should be stripped.

To right-justify, left-justify, and center a string


• The rjust() and ljust() string methods return a padded version of the string they are called on, with spaces inserted
to justify the text.
• The first argument to both methods is an integer length for the justified string.

Example:
“hello”.rjust(10)
Output= hello
“hello”.rjust(25)
Output= hello
“hello”.rjust(10)
Output=hello

• 'Hello'.rjust(10) says that we want to right-justify 'Hello' in a string of total length 10. 'Hello' is five characters, so
five spaces will be added to its left, giving us a string of 10 characters with 'Hello' justified right.
• An optional second argument to rjust() and ljust() will specify a fill character other than a space character.
Example:
“hello”.rjust(20,’*’)
Output=*************************hello

“hello”.ljust(20,’@’)
Output=hello@@@@@@@@@@@@@@@@@@@@@@@@@@@

“hello”.center(10)
Output = hello

“hello”.center(20,’=’)
Output= ===============hello===============

join() and split()

6
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

• The join() method is useful when we have a list of strings that need to be joined together into a single string value.
• The join() method is called on a string, gets passed a list of strings, and returns a string. The returned string is the
concatenation of each string in the passed-in list.

Example:
‘,’.join([‘cat’,’rat’,’bat’])
Output= cat,rat,bat

‘ ‘.join([‘my’,’name’,’is’,’modi’])
Output= my name is modi

‘india’.join([‘my’,’name’,’is’,’modi’])
myindianameindiaisindiamodi

• The split() method is called on a string value and returns a list of strings.

Example:
“my name is modi”.split()
Output=[“my”,”name”,’is”,”modi”]

“myindianameindiaisindiamodi”.split(“india”)
Output = [“my”,”name”,’is”,”modi”]

isalpha(),isdecimal(),isalnum()
• isalpha() returns True if the string consists only of letters and is not blank.
• isdecimal() returns True if the string consists only of numeric characters and is not blank.
• isalnum() returns True if the string consists only of letters and numbers and is not blank.

startswith() and endswith()


• The startswith() and endswith() methods return True if the string value they are called on begins or ends
(respectively) with the string passed to the method; otherwise, they return False.

7
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

Python program to count the number of words, digits, uppercase letters, and lowercase letters

sentence = input("Enter a sentence: ")


word, digit, ucase, lcase = 0, 0, 0, 0
listword = sentence.split()
w = len(listword)
for char in sentence:
if char.isdigit():
digit = digit + 1
elif char.isupper():
ucase = ucase + 1
elif char.islower():
lcase = lcase + 1

print ("No of Words: ", word)


print ("No of Digits: ", digit)
print ("No of Uppercase letters: ", ucase)
print ("No of Lowercase letters: ", lcase)

Pretty Printing
➢ Importing pprint module will provide access to the pprint() and pformat() functions that
will “pretty print” a dictionary’s values.
➢ This is helpful when we want a cleaner display of the items in a dictionary than what
print() provides and also it is helpful when the dictionary itself contains nested lists or
dictionaries..

8
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

Develop a Python program find the total size of all the files in the given directory.

>>> totalSize = 0
>>> for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32',
filename))
>>> print(totalSize)
1117846456
Develop a Python program to count the number of lines in a file.

file = open("jitd.txt", "r")


Counter = 0

# Reading from file


Content = file.read()
CoList = Content.split("\n")

for i in CoList:
if i:
Counter += 1

print("number of lines in the file")


print(Counter)
Briefly explain the steps involved in adding bullets to wiki-Markup with appropriate code.
➢ The bulletPointAdder.py script will get the text from the clipboard, add a star and space to the

9
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

beginning of each line, and then paste this new text to the clipboard.

Step 1: Copy and Paste from the Clipboard


➢ You want the bulletPointAdder.py program to do the following:
1. Paste text from the clipboard
2. Do something to it
3. Copy the new text to the clipboard
➢ Steps 1 and 3 are pretty straightforward and involve the pyperclip.copy() and pyperclip.paste()
functions. saving the following program as bulletPointAdder.py:

Step 2: Separate the Lines of Text and Add the Star


➢ The call to pyperclip.paste() returns all the text on the clipboard as one big string. If we used the “List
of Lists of Lists” example, the string stored in text.
➢ The \n newline characters in this string cause it to be displayed with multiple lines when it is printed or
pasted from the clipboard.
➢ We could write code that searches for each \n newline character in the string and then adds

10
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

the star just after that. But it would be easier to use the split() method to return a list of strings, one
for each line in the original string, and then add the star to the front of each string in the list.

Step 3: Join the Modified Lines


➢ The lines list now contains modified lines that start with stars.
➢ pyperclip.copy() is expecting a single string value, not a list of string values. To make this single
string value, pass lines into the join() method to get a single string joined from the list’s strings.

Project: Password Locker


Step 1: Program Design and Data Structures
➢ We have to run this program with a command line argument that is the account’s name-
-for instance, email or blog. That account’s password will be copied to the clipboard so that the user can
paste it into a Password field. The user can have long, complicated passwords without having to
memorize them.

comment that briefly describes the program. Since we want to associate each account’s name
with its password, we can store these as strings in a dictionary.

11
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

Step 2: Handle Command Line Arguments


➢ The command line arguments will be stored in the variable sys.argv.
➢ The first item in the sys.argv list should always be a string containing the program’s filename
('pw.py'), and the second item should be the first command line argument.

Step 3: Copy the Right Password


➢ The account name is stored as a string in the variable account, you need to see whether it exists in the
PASSWORDS dictionary as a key. If so, you want to copy the key’s value to the clipboard using
pyperclip.copy().

12
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)


➢ This new code looks in the PASSWORDS dictionary for the account name. If the account name is a key
in the dictionary, we get the value corresponding to that key, copy it to the clipboard, and print a
message saying that we copied the value. Otherwise, we print a message saying there’s no account
with that name.

13
IMPORTANT QUESTION AND ANSWERS FOR 2ND IA
Introduction to Python Programmin(BPCLK205B)

Checking Path Validity


• The os.path module provides functions to check whether a given path exists and whether it is
a file or folder.
• 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.
>>> os.path.exists('C:\\Windows') True
>>> os.path.exists('C:\\some_made_up_folder') False
>>> os.path.isdir('C:\\Windows\\System32') True
>>> os.path.isfile('C:\\Windows\\System32') False
>>> os.path.isdir('C:\\Windows\\System32\\calc.exe') False
>>> os.path.isfile('C:\\Windows\\System32\\calc.exe') True

Lab Programs from 6 to 8

14

You might also like