OS module
os
module provides diverse functionalities to interact with the operating system. We’ll take a look at some of the important functions.
1
2
3
4
| import os
def back_to_base():
os.chdir('/Users/jasonlee/Desktop/AI_STUDY/Python/os_test_dir')
|
os.getcwd()
os.getcwd()
returns the current workind directory(cwd).
1
2
3
4
| back_to_base()
current_cwd = os.getcwd()
print("Current working directory: %s" % (current_cwd))
|
1
| Current working directory: /Users/jasonlee/Desktop/AI_STUDY/Python/os_test_dir
|
os.chdir(path)
As the name suggests, it changes the working directory to path
1
2
3
4
5
6
7
8
9
| back_to_base()
current_cwd = os.getcwd()
print("Current working directory: %s" % (current_cwd))
os.chdir('../')
new_cwd = os.getcwd()
print("New working directory: %s" % (new_cwd))
|
1
2
| Current working directory: /Users/jasonlee/Desktop/AI_STUDY/Python/os_test_dir
New working directory: /Users/jasonlee/Desktop/AI_STUDY/Python
|
os.listdir(path='.')
os.listdir() gives a list of all entries(files and directories). If no argument is passed, the default is the current working directory. It does not show the special entires .
and ..
such as .bashrc
.
1
2
3
4
5
6
| back_to_base()
os.chdir('../')
print(os.listdir())
back_to_base()
|
1
| ['Week1_Quiz.ipynb', 'os_test_dir', '1_Namespace_Scope.ipynb', 'Iterator_generator.ipynb', 'argparse_tut.py', '__pycache__', 'iterator_generator_quiz.ipynb', 'os module.ipynb', '.ipynb_checkpoints', 'special methods.ipynb', '2_Class.ipynb', '3_Inheritance.ipynb', 'Iterator_generator.md']
|
os.mkdir(path)
os.mkdir()
is used to create a directory. If the directory already exists, it raises FileExistsError
.
1
2
3
4
| back_to_base()
os.mkdir('new_dir')
os.listdir()
|
os.makedirs(path)
Unlike os.mkdir()
, os.makedirs()
recursively creates the directory which means that even if the intermediate paths do not exist, it creates all of them. For example, let’s say we have no directory in our current working directory and if we do os.makedirs('./a/b/c/d/e/f/g')
, then it will create all those a
,..,g
directory recursively
1
2
3
4
5
6
| back_to_base()
os.makedirs('./a/b')
print(os.listdir())
os.chdir('a')
print(os.listdir())
|
1
2
| ['a', 'new_dir']
['b']
|
os.remove(path)
os.remove()
removes the file path. It raises an IsADirectoryError
exception if path refers to a directory.
1
2
3
4
5
6
7
8
9
10
11
12
13
| back_to_base()
# Create a file
f = open('./test.txt', 'w')
f.write('hello')
f.close()
print("Before remove:", os.listdir())
# Remove a file
os.remove('./test.txt')
print("After remove:", os.listdir())
|
1
2
| Before remove: ['a', 'new_dir', 'test.txt']
After remove: ['a', 'new_dir']
|
os.rmdir(path)
os.rmdir()
removes a directory. It will raise FileNotFoundError
or OSError
if the specified path does not exist or not an empty directory.
1
2
3
4
5
6
7
8
| back_to_base()
print("Before remove directory new_dir:", os.listdir())
# Remove test_dir
os.rmdir('new_dir')
print('After remove directory test_dir:', os.listdir())
|
1
2
| Before remove directory new_dir: ['a', 'new_dir']
After remove directory test_dir: ['a']
|
os.rename(src, dst)
Rename the file or directory src
to dst
. OSError
will be raised if dst
already exists.
1
2
3
4
5
| print("Before renaming a", os.listdir())
os.rename('a','aaa')
print("After renaming a to aaa", os.listdir())
|
1
2
| Before renaming a ['a']
After renaming a to aaa ['aaa']
|
os.path.isdir(path)
Return True
if the given path is an existing directory, otherwise False
.
1
2
3
| print(os.listdir())
print(os.path.isdir('aaa'))
|
os.path.isfile(path)
Return True
if the fiven path is an existing file, otherwise False
1
2
3
4
5
| with open('test.txt', 'w') as f:
f.write('hello')
print(os.listdir())
print(os.path.isfile('test.txt'))
|
1
2
| ['aaa', 'test.txt']
True
|
os.path.exists(path)
Return True
if path
exists which means it checks the existence of both file and directory.
1
2
3
| print(os.listdir())
print(os.path.exists('aaa'))
print(os.path.exists('test.txt'))
|
1
2
3
| ['aaa', 'test.txt']
True
True
|
os.path.join(path, *path)
This joins one or multiple paths with exactly one separater /
and return the result as str
. If the last part is empty, then the result will end with /
1
| os.path.join('d1','d2','d3')
|
1
| os.path.join("d1",'','d2') # last part is not empty
|
1
| os.path.join('d1','') # last part is empty
|