web-profile

Python os

import os
import errno

# print(dir(os)) # prints all the available attributes and methods

print(os.getcwd()) # D:\python\os (current working directory)

os.chdir('temp') # change current working directory

print(os.getcwd()) # D:\python\os\temp

print(os.listdir()) # ['temp2', 'temp3'] (directory list)

# os.mkdir('temp4') # create directory

try: # catch FileExistsError error
    os.mkdir('temp4')
except OSError as exc:
    if exc.errno != errno.EEXIST:
        raise
    pass

os.makedirs('temp5/sub', exist_ok=True) # create directory with subdirs; exist_ok for FileExistsError

print(os.listdir()) # ['temp2', 'temp3', 'temp4', 'temp5']

os.rmdir('temp4') # delete directory
os.removedirs('temp5/sub') # delete directory and subdirectories

print(os.listdir()) # ['temp2', 'temp3']

# os.rename('test.txt', 'demo.txt')

print(os.stat('demo.txt')) # file info
# Useful stat results: st_size (bytes), st_mtime (time stamp)

# To see entire directory tree and files within os.walk is a generator
# that yields a tuple of 3 values as it walks the directory tree
for dirpath, dirnames, filenames in os.walk(os.getcwd()): 
    print('Current Path:', dirpath)
    print('Directories:', dirnames)
    print('Files:', filenames)
    print()

'''
Current Path: D:\python\os\temp
Directories: ['temp2', 'temp3']
Files: ['demo.txt']

Current Path: D:\python\os\temp\temp2
Directories: []
Files: []

Current Path: D:\python\os\temp\temp3
Directories: []
Files: []
'''

print(os.environ.get('HOME')) # C:\Users\jim

file_path = os.path.join(os.environ.get('HOME'), 'test.txt')
print(file_path) # C:\Users\jim\test.txt

# create file C:\Users\jim\test.txt
# with open(file_path, 'w') as f:
#     f.write(' ')

print(os.path.basename('temp/temp2/test.txt')) # test.txt
print(os.path.dirname('temp/temp2/test.txt')) # temp/temp2
print(os.path.split('temp/temp2/test.txt')) # ('temp/temp2', 'test.txt')

print(os.path.exists(os.environ.get('HOME'))) # True
print(os.path.isdir(os.environ.get('HOME'))) # True
print(os.path.isfile(os.environ.get('HOME'))) # False

print(os.path.splitext('temp/temp2/test.txt')) # ('temp/temp2/test', '.txt')

# print(dir(os.path)) # prints all the available attributes and methods

Leave a Reply

Your email address will not be published.