1.
File join method
import os
print(os.path.join('usr', 'bin', 'spam'))
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
print(os.path.join('C:\\Users\\asweigart', filename))
Output:
usr\bin\spam
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
2. Get and Change working directory
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
3. Directory name and Base name
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
5. Illustration of shelf files
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
import os # Provides functions for interacting with the operating system.
import sys # Provide numerous tools to deal with filenames, paths, directories
import pathlib # Offers classes representing filesystem paths with semantics
appropriate for different os
import zipfile # Provides tools to create, read, write, append, and list a ZIP
file
dirName = input("Enter Directory name that you want to zip : ") # Directory name
to be entered as c:\dirName
if not os.path.isdir(dirName): # Check if directory exists
print("Directory", dirName, "doesn’t exist")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
print(curDirectory) # Display the directory entered
with zipfile.ZipFile("myZip.zip", mode="w") as archive: # Creates a ZIP file in
which the files to be compressed are added
for file_path in curDirectory.rglob("*"): # Returns a list of files
or folders matching the path specified in the argument.
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully") # C:\Users\MPS\AppData\
Local\Programs\Python\Python311\myZip.zip
else:
print("Error in creating zip archive")
--------------------------------------------------------------------
1. Create Complex Numbers
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
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output:
3
4. Different Types of Lists
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list4 = ["abc", 34, True, 40, "male"]
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
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[1])
print(thislist[-1])
print(thislist[2:5])
print(thislist[:4])
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output:
banana
mango
['cherry', 'orange', 'kiwi']
['apple', 'banana', 'cherry', 'orange']
Yes, 'apple' is in the fruits list
6. Sorting Lists with sort Method
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
Output:
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
[100, 82, 65, 50, 23]