To share this page click on the buttons below;
Filesystem functions
Modules
Functions to handle files are in os
module.
Functions to handle temporary directories are in tempfile
module.
import tempfile
import os
Exist
To check if a path
exists
os.path.exist( <path> )
Get
To get all the items in a directory
os.listdir( <path> )
Current
To get current directory
os.getcwd()
Create
To make a new directory
os.mkdir(path)
Exceptions: OSError
To make an entire path of directories
os.makedirs(path)
Exceptions: OSError
To make a temporary directory
import tempfile
# create a temporary directory
with tempfile.TemporaryDirectory() as directory:
print('The created temporary directory is %s' % directory)
# directory and its contents have been removed by this point
Delete
To delete a directory
os.rmdir(path)
Exceptions: OSError
To delete a tree of directories
Use rmtree()
in module shutil.
Rename
To rename files
os.rename(<old name of file or directory>, <new name of file or directory>)
Move
To move files It is possible to move a file by renaming it's path
os.rename(<old name of file or directory>, <new name of file or directory>)
or use move from shutil module
import shutil
# Move a file from the directory d1 to d2
shutil.move(<old position>, <new position>)
Copy
To copy files
import shutil
shutil.copyfile(<source_file>, <destination_file>)
# OTHER POSSIBILITY
shutil.copy(<source_file>, <destination_file>) # dst can be a folder
shutil.copy2() # to preserve timestamp
To share this page click on the buttons below;