1. What is OS Module?
The OS module provides a portable way of using operating system dependent functionality.
2. Importing OS module
import os
# check all attributes and methods
print(dir(os))
3. Useful methods of OS module
# Get current working directory
print(os.getcwd(), '\n')
# Change working direcotry
os.chdir('...')
# List directory : List all files and directory in current working directory
print(os.listdir(), '\n')
# Make new directory
os.mkdir('...')
# Remove directory
os.rmdir('...')
# Rename directory
os.rename('prev.txt', 'new.txt')
# Check stat of file
print(os.stat('03 Integers and Floats - Working with Numeric Data .ipynb'))
# We can extract more complicated data with dot attributes.
3.1 Extract made time of files
# Find made time of files :
# Useful for check application that has a lot of files that have been updated or created recently
import os
from datetime import datetime
mod_time = os.stat('file.txt').st_mtime
print(datetime.fromtimestamp(mod_time))
3.2 Yield directory path tree
# Yield directory path tree
for dirpath, dirnames, filenames in os.walk('../'):
print(f"Current path: {dirpath}")
print(f"Directories: {dirnames}")
print(f"Files : {filenames}")
print()
Source from :
- https://docs.python.org/3/library/os.html
- https://www.youtube.com/watch?v=tJxcKyFMTGo&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7&index=10
'Language > Python' 카테고리의 다른 글
[Syntax] Special arguments *args and **kwargs (0) | 2022.10.14 |
---|---|
[Error] Why does substring slicing with index out of range work? (1) | 2022.10.13 |
[sys] The way to import module not found (0) | 2022.10.03 |
[OOP] Implement Logic Gates using Class Inheritance (0) | 2022.10.03 |
[OOP] Creating Fraction Class using OOP (1) | 2022.09.30 |