Python - File, directory manipulation


First you should import os modules.


import os

Get current working folder



import os
dir = os.getcwd() 
print(dir)


Change current working directory



import os
dir = os.getcwd() 
print(dir)
os.chdir("/home")
dir = os.getcwd() 
print(dir)


Get absolute path for specific path



import os
dir = os.getcwd() 
print(dir)
os.chdir("/home")
dir = os.getcwd() 
print(dir)
os.chdir("pi")
abs_dir = os.path.abspath('./rpi-rgb-led-matrix')
print(abs_dir) # '/home/pi/rpi-rgb-led-matrix'

Get only directory name in path


import os
dir = os.getcwd() 
print(dir)
os.chdir("/home")
dir = os.getcwd() 
print(dir)
os.chdir("pi")
abs_path = os.path.abspath('./rpi-rgb-led-matrix') 
print(abs_path)
dir_name = os.path.dirname('/home/pi/rpi-rgb-led-matrix/README.md')
print(dir_name) # '/home/pi/rpi-rgb-led-matrix'



Get only file name in path


import os
dir = os.getcwd() 
print(dir)
os.chdir("/home")
dir = os.getcwd() 
print(dir)
os.chdir("pi")
abs_path = os.path.abspath('./rpi-rgb-led-matrix') 
print(abs_path)
dir_name = os.path.dirname('/home/pi/rpi-rgb-led-matrix/README.md')
print(dir_name) # '/home/pi/rpi-rgb-led-matrix'
filename = os.path.basename('/home/pi/rpi-rgb-led-matrix/README.md')
print(filename) # 'README.md'


Split directory name and file name in path


import os
dir = os.getcwd() 
print(dir)
os.chdir("/home")
dir = os.getcwd() 
print(dir)
os.chdir("pi")
dir, file = os.path.split('/home/pi/rpi-rgb-led-matrix/README.md')
print(dir) # '/home/pi/rpi-rgb-led-matrix'
print(file) # 'README.md'


Merge paths to create new path


import os
new_path = os.path.join('/home', 'a', 'b')
print(new_path) #/home/a/b


Filename extension check


import os
filename = '/home/pi/rpi-rgb-led-matrix/README.md'
ok = filename.endswith('.md')
print(ok) # True


File name and extension separation


import os
filename = '/home/pi/rpi-rgb-led-matrix/README.md'
name, ext = os.path.splitext(filename)
print(name) #'/home/pi/rpi-rgb-led-matrix/README
print(ext) # .md


Check if file or directory path exists


import os
filename = '/home/pi/rpi-rgb-led-matrix/README.md'
ok = os.path.exists(filename)
print(ok) #True

 

Check if directory path exists


import os
filename = '/home/pi/rpi-rgb-led-matrix/README.md'
dirname =  '/home/pi/rpi-rgb-led-matrix'
ok = os.path.isdir(filename)
print(ok) #False
ok = os.path.isdir(dirname)
print(ok) #True


Check if file path exists


import os
filename = '/home/pi/rpi-rgb-led-matrix/README.md'
dirname =  '/home/pi/rpi-rgb-led-matrix'
ok = os.path.isfile(filename)
print(ok) #True
ok = os.path.isfile(dirname)
print(ok) #False

Get file size


import os
filename = '/home/pi/rpi-rgb-led-matrix/README.md'
size = os.path.getsize(filename)
print(size) #30875


Get file information

This code prints last modified time of the file.

import os
from datetime import datetime
filename = '/home/pi/rpi-rgb-led-matrix/README.md'
ret = os.stat(filename)
print(ret)
mod_time = ret.st_mtime
print('modified : ' + datetime.fromtimestamp(mod_time))

The output looks like this:


root@raspberrypi:/tmp# python3 dir.py 
os.stat_result(st_mode=33188, st_ino=131820, st_dev=45826, st_nlink=1, st_uid=1000, st_gid=1000, st_size=30875, st_atime=1570463433, st_mtime=1570463433, st_ctime=1577865179)
modified : 2019-10-08 00:50:33

As you can see from the output, the file size can also be obtained with this function.

List of files / subdirectories in a directory


import os

filenames = os.listdir('./')
for filename in filenames:
    if True == os.path.isdir(filename):
        print('dir:' + filename)
    else:    
        size = os.path.getsize(filename)
        print('%s --- %d bytes'%(filename, size))


Navigating directories with os.walk


import os
from datetime import datetime
for dirpath, subdirs, filenames in os.walk('F:\\study'):
    print('Current Directory:', dirpath)
    print('Sub Directories:', subdirs)
    print('Files:', filenames)
    print()

The output looks like this. As you can see, os.walk function generates the file names in a directory tree by walking the tree either top-down or bottom-up:


Current Directory: F:\study
Sub Directories: ['opencv']
Files: ['udpserver.py']

Current Directory: F:\study\opencv
Sub Directories: []
Files: ['animation.gif', 'animation.mp4', 'animation_rotate.py', 'biden.jpg', 'biden.png', 'exam1.py', 'exam2.py', 'exam3.py', 'exam4-numpy.py', 'exam4.py', 'exam5.py', 'exam6.py', 'rotate.py', 'run.jpg', 'sbear.png', 'smask.jpg', 'split.py']

Create a new folder


import os
dirname = '/tmp/hello/yes' #no hello directory
try:
    os.mkdir(dirname)
except FileNotFoundError:   #python3 only
    print('Error : ' + dirname + ' Not found ')

except FileExistsError:   
    print('Info : ' + dirname  ++ ' already exist ')
    
dirname = '/tmp/hello'
try:
    os.mkdir(dirname)
    print('Success : ' + dirname + ' Create success')

except FileNotFoundError:   #python3 only
    print('Error : ' + dirname + ' Not found ')


os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.


import os
dirname = '/tmp/hello/yes' #no hello directory
try:
    os.makedirs(dirname)
    print('Success : ' + dirname + ' Create success')

except FileNotFoundError:   #python3 only
    print('Error : ' + dirname + ' Not found ')

Delete a folder


import os
dirname = '/tmp/hello/yes' #not exist
try:
    os.rmdir(dirname)
except FileNotFoundError:   #python3 only
    print('Error : ' + dirname + ' Not found ')

dirname = '/tmp/hello2'  #hello2 contains files
try:
    os.rmdir(dirname)
    print('Success : ' + dirname + ' delete success')

except OSError as err:   
    print("OS error: {0}".format(err))
    
dirname = '/tmp/hello' #empty directory
try:
    os.rmdir(dirname)
    print('Success : ' + dirname + ' delete success')

except FileNotFoundError:   #python3 only
    print('Error : ' + dirname + ' Not found ')

os.removedirs() method in Python is used to remove directories recursively. If the leaf directory in the specified path is successfully removed, then os.removedirs() tries to successively remove every parent directory mentioned in path until an error is raised. The raised error is ignored because generally error is raised because directory to be deleted is not empty.


import os
dirname = '/tmp/hello/hello2' 

try:
    os.makedirs(dirname)
except FileNotFoundError:   #python3 only
    print('makedirs Error : ' + dirname + ' Not found ')

try:
    os.rmdir(dirname) #only removes hello2 directory
except FileNotFoundError:   #python3 only
    print('rmdir Error : ' + dirname + ' Not found ')

try:
    os.makedirs(dirname)
    os.removedirs(dirname)  #remove all (hello, hello2) directories
except FileNotFoundError:   #python3 only
    print('removedirs Error : ' + dirname + ' Not found ')


Delete a file


import os
filename = '/tmp/hello/aaa' #not exist
try:
    os.remove(filename)
    print('Success : ' + filename + ' delete success')
except FileNotFoundError as err:   #python3 only
    print("FileNotFoundErroor  error: {0}".format(err))

filename = '/tmp/hello' #empty directory
try:
    os.remove(filename)
    print('Success : ' + filename + ' delete success')

except FileNotFoundError as err:   #python3 only
    print("FileNotFoundErroor  error: {0}".format(err))


Rename file or path


import os
dirname = '/tmp/hello'      #Not exist 
n_dirname = '/tmp/hello3'   #Not exist 
try:
    os.rename(dirname, n_dirname)
    print('Success : ' + dirname + ' rename success')
except FileNotFoundError as err:   #python3 only
    print("FileNotFoundErroor  error: {0}".format(err))

dirname = '/tmp/hello2'      
n_dirname = '/tmp/hello4'   #exist 
try:
    os.rename(dirname, n_dirname)
    print('Success : ' + dirname + ' rename success')
except FileNotFoundError as err:   #python3 only
    print("FileNotFoundErroor  error: {0}".format(err))










댓글

이 블로그의 인기 게시물

VSCode - Lua programming and debugging

Remote C/C++ Debugging with VSCode #1 - Installation and simple debugging

Remote Python Debugging with VSCode