Additional Python Programs
Additional Python Programs
import os
print(os.path.join('usr', 'bin', 'spam'))
Output:
usr\bin\spam
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
import os
print(os.getcwd())
os.chdir('C:\\Windows\\System32')
print(os.getcwd())
Output:
E:\Python Programming 22PLC15B II Sem May 2023\Lab Programs
C:\Windows\System32
import os
path = 'C:\\Windows\\System32\\calc.exe'
print(os.path.basename(path))
print(os.path.dirname(path))
calcFilePath = 'C:\\Windows\\System32\\calc.exe'
print(os.path.split(calcFilePath))
Output:
calc.exe
C:\Windows\System32
('C:\\Windows\\System32', 'calc.exe')
4. File size
import os
totalSize = 0
for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32',
filename))
print(totalSize)
Output:
2010348675
import shelve
shelfFile = shelve.open('mydata')
cats = ['Zophie', 'Pooka', 'Simon', 'Bezriwal', 'Pappudu']
shelfFile['myCats'] = cats # Save list on to shelfFile
shelfFile.close()
shelfFile = shelve.open('mydata') # Reopen and retrieve the data from shelf files.
print(type(shelfFile))
print(shelfFile['myCats'])
Output:
<class 'shelve.DbfilenameShelf'>
['Zophie', 'Pooka', 'Simon', 'Bezriwal', 'Pappudu']
6. setDefault Method
import pprint
message = 'R V Institute of Technology, J P Nagar, Bengaluru'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
#print(count)
pprint.pprint(count)
7. File zipping
dirName = input("Enter Directory name that you want to zip : ") # Directory name
to be entered as c:\dirName
curDirectory = pathlib.Path(dirName)
print(curDirectory) # Display the directory entered
--------------------------------------------------------------------
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'complex'>
<class 'complex'>
<class 'complex'>
2. Type Conversion
x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")
print(x)
print(y)
print(z)
print(w)
Output:
1.0
2.8
3.0
4.2
3. Length of List
Output:
3
print(list1)
print(list2)
print(list3)
print(list4)
Output:
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]
['abc', 34, True, 40, 'male']
5. Accessing Lists
Output:
banana
mango
['cherry', 'orange', 'kiwi']
['apple', 'banana', 'cherry', 'orange']
Yes, 'apple' is in the fruits list
Output:
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
[100, 82, 65, 50, 23]