Python Imp 3
Python Imp 3
5. Explain with suitable Python program segments: (i) os.path.basename() (ii) os.path.join()
7. Explain reading and saving python program variables using shelve module with suitable
Python program.
8. Explain how to read specific lines from a file? Illustrate with python Program.
Programs
1. Develop a Python program find the total size of all the files in the given directory.
3. Develop a Python program to read and print the contents of a text file.
1. Explain Python string handling methods with examples: split(),
endswith(), center(), lstrip().
split():
Split method called on a string value and returns a list of strings. The split()
method splits a string into a list.
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
By default, the string 'My name is Simon' is split wherever whitespace
characters such as the space, tab, or newline characters are found. These
whitespace characters are not included in the strings in the returned list.
For example
>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']
endswith():
endswith() methods return True if the string value they are called ends with
the string passed to the method; otherwise, they return False.
>>> 'Hello world!'.endswith('world!')
True
>>> 'abc123'.endswith('12')
False
>>> 'Hello world!'.endswith('Hello world!')
True
center():
The center() string method works like ljust() and rjust() but centers the text
rather than justifying it to the left or right.
>>> 'Hello'.center(20)
' Hello '
>>> 'Hello'.center(20, '=')
'=======Hello========'
lstrip():
The lstrip() method will remove whitespace characters from the right ends,
respectively.
spam = ' Hello World '
>>> spam.lstrip()
'Hello World '
startswith():
The startswith() method return True if the string value they are called on
begins with the string passed to the method; otherwise, they return False.
>>> 'Hello world!'.startswith('Hello')
True
>>> 'abc123'.startswith('abcdef')
False
>>> 'Hello world!'.startswith('Hello world!')
True
rjust():
The rjust() string method return a padded version of the string they are called
on, with spaces inserted to justify the text. The first argument is an integer
length for the justified string.
>>> 'Hello'.rjust(10)
' Hello'
>>> 'Hello'.rjust(20)
' Hello'
strip():
Sometimes you may want to strip off whitespace characters (space, tab, and
newline) from the left side, right side, or both sides of a string. The strip()
string method will return a new string without any whitespace characters at
the beginning or end.
>>> spam = ' Hello World '
>>> spam.strip()
'Hello World'
rstrip():
The rstrip() methods will remove whitespace characters from the left ends,
respectively.
>>> spam = ' Hello World '
>>> spam.rstrip()
' Hello World'
• isalpha(): returns True if the string consists only of letters and is not blank.
• isalnum(): returns True if the string consists only of letters and numbers
and is not blank.
• isdecimal(): returns True if the string consists only of numeric characters
and is not blank
• isspace(): returns True if the string consists only of spaces, tabs, and
newlines
and is not blank.
• istitle(): returns True if the string consists only of words that begin with
an uppercase letter followed by only lowercase letters.
>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
>>> 'hello123'.isalnum()
True
>>> '123'.isdecimal()
True
>>> ' '.isspace()
True
>>> 'This Is Title Case'.istitle()
True
>>> 'This Is not Title Case'.istitle()
False
>>> 'This Is NOT Title Case Either'.istitle()
False
The isupper() and islower() methods will return a Boolean True value if
the string has at least one letter and all the letters are uppercase or lowercase,
respectively. Otherwise, the method returns False.
For example
>>> path = 'C:\\Windows\\System32\\calc.exe'
>>> os.path.basename(path)
'calc.exe'
(ii) os.path.join()
On Windows, paths are written using backslashes (\) as the separator between
folder names. OS X and Linux, however, use the forward slash (/) as their path
separator. If you want your programs to work on all operating systems, you
will have to write your Python scripts to handle both cases.
Fortunately, this is simple to do with the os.path.join() function. If you pass it
the string values of individual file and folder names in your path, os.path.join()
will return a string with a file path using the correct path separators.
>>> import os
>>> os.path.join('usr', 'bin', 'spam')
'usr\\bin\\spam'
6. Discuss different paths of file system.
Absolute and Relative Paths
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. These are not real folders but
special names that can be used in a path. A single period (“dot”) for a folder
name is shorthand for “this directory.” Two periods (“dot-dot”) means “the
parent folder.”
Figure is an example of some folders and files. When the current working
directory is set to C:\bacon, the relative paths for the other folders and files
are set as they are in the figure.
7. Explain reading and saving python program variables using shelve
module with suitable Python program.
You can save variables in your Python programs to binary shelf files using the
shelve module. This way, your program can restore data to variables from the
hard drive. The shelve module will let you add Save and Open features to your
program. For example, if you ran a program and entered some configuration
settings, you could save those settings to a shelf file and then have the program
load them the next time it is run.
To read and write data using the shelve module, you first import shelve. Call
shelve.open() and pass it a filename, and then store the returned shelf value in
a variable. You can make changes to the shelf value as if it were a dictionary.
When you’re done, call close() on the shelf value. Here, our shelf value is
stored in shelfFile. We create a list cats and write shelfFile['cats'] = cats to
store the list in shelfFile as a value associated with the key 'cats' (like in a
dictionary). Then we call close() on shelfFile.
8. Explain how to read specific lines from a file? Illustrate with python
Program.
Text files are composed of plain text content. Text files are also known as flat
files or plain files. Python provides easy support to read and access the content
within the file. Text files are first opened and then the content is accessed from
it in the order of lines. By default, the line numbers begin with the 0th index.
Program
file = open('test.txt')
content = file.readlines()
print("tenth line")
print(content[9])
print("first three lines")
print(content[0:3])
Programs
1. Develop a Python program find the total size of all the files in the given
directory.
import os
size = 0
Folderpath = 'C:/Users/Documents/R'
for path, dirs, files in os.walk(Folderpath):
for f in files:
fp = os.path.join(path, f)
size += os.stat(fp).st_size
print("Folder size: " + str(size))
2. Develop a python program to determine whether the given string is a
palindrome or not a palindrome.
def isPalindrome(s):
return s == s[::-1]
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")