Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- filePath = r'c:\spam'
- #create path
- fullPath = os.path.join(filePath, 'folder', 'eggs.png')
- print(fullPath)
- #get working directory
- os.getcwd()
- #change working directory
- os.chdir('c:\\drivers')
- #absolute/relative path
- os.path.abspath('..\\drivers')
- os.path.isabspath()
- os.path.relpath(fullpath, 'c\\spam') #relative path from a starting point
- os.path.dirname(fullpath)
- os.path.basename(fullpath)
- #exists
- os.path.exists(fullpath)
- os.path.isfile(fullpath)
- os.path.isfolder(fullpath)
- os.path.getsize(fullpath)
- os.listir('c:\\driver')
- os.makedirs('c:\\driver2')
- ########################################
- #reading/writing files
- ########################################
- filePath = r'c:\spam\myFile.txt'
- helloFile = open(filePath) #read mode
- content = helloFile.read() #to read the file twice I need to call again open
- helloFile.close()
- lines = helloFile.readlines()
- helloFile = open(filePath, 'w') #write mode
- helloFile.write('Bla') #it does not add the \n automatically
- #shelve files; allow to store list, dictionary and not-text data to
- #a binary file.
- import shelve
- shelFile = shelve.open('mydata')
- shelFile['cats'] = ['bla', 'ciao', 'miao']
- shelFile.close()
- #can be read with:
- shelFile = shelve.open('mydata')
- print(shelFile['cats'])
- #it works like a dictionary
- shelFile.keys()
- shelFile.values()
- ########################################
- #copy/move
- ########################################
- import shutil
- //copy single file
- shutil.copy(fileSrcPath, dirPath)
- shutil.copy(fileSrcPath, fileTargetPath) //copy and rename
- //copy a directory
- shutil.copytree(SrcFolder, targetFolder)
- shutil.move(fileSrcPath, dirPath)
- shutil.move(fileSrcPath, fileTargetPath) //rename
- ########################################
- #deletion
- ########################################
- os.unlink(fileName)
- os.rmdir(dirName) #remove directory if empty
- import shutil
- shutil.rmtree(dirName) #delete the folder and its content
- import send2trash
- send2trash.send2trash(fileName) #send to trash instead of permanently removing
- ########################################
- #walk a folder tree and allow to do operations in each level of the tree
- ########################################
- for folderName, subfolders, filenames in os.walk(folderName) :
- print('Folder is' + folderName)
- print('Subfolders of ' + folderName + ' are ' + str(subfolders))
- print('Filenames of ' + folderName + ' are ' + str(filenames))
- for subfolder in subfolders :
- #...do something
- for file in filenames :
- #...do something
Advertisement
Add Comment
Please, Sign In to add comment