10. OS Flashcards
os module
os.path.join(‘folder1’,’folder2’,’file.png’)
avoid different system using / or \
current working directory
os.getcwd()
change directory
os.chdir
relative file path
.\ same folder as in cwd
..\ parent folder
file path string
1) ‘C:\user\files’
2) r’C:\user\files’
converting path to raw string
myVariable = ‘This string is supposed to be raw '
print(r’%s’ %myVariable)
but technically no different on the string after parse
check exist
os.path.exists(‘path’)
isfile
isdir
break up a path
os. path.dirname()
os. path.basename()
whole director
os.listdir
use with isfile
create a folder
os.makedirs => create all of the folder
open txt file
myfile = open('abc.txt) myfile = open('abc.txt, 'r') myfile = open('abc.txt, 'w') -> it creates the file if not exist myfile = open('abc.txt, 'a') -> it creates the file if not exist
mytext = myfile.read()
myfile.close()
shelve module
shelve file is a binary File, very similar to a dictionary.
shelve file has keys and values
can store list
shelfFile = shelve.open(‘mydata’)
shelfFile[‘Cats’] = [‘a’,’b’,’c’]
shelfFile[‘Dogs’] = [‘d’,’e’,’f’]
shelfFile.close()
print(list(shelfFile.keys()))
shutil module
shutil. copy (can rename while copy)
shutil. copytree
shutil. move (this is also used for rename)
shutil. rmtree (this will remove the folder and all content)
deleting file or path
os. unlink(‘abc.txt’) -> File
os. rmdir(‘my path’) -> remove folder that is empty
deleting file or path
os. unlink(‘abc.txt’) -> File
os. rmdir(‘my path’) -> remove folder that is empty
note remove permenantly