본문 바로가기

Language/Python

[os] User Underlying Operating System

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 :