Python File System Operation Snippets Collection

In this post, I’ll share some simple snippet to do various file system operation. Pretty much as a bookmark for my own usage, in case I needed it someday.

How to get current working directory:

import os
os.getcwd()

How to change working directory:

import os
os.chdir('/tmp/')

How to list directory contents:

import os
os.listdir('/tmp/')

How to check if directory / file exists:

import os
os.path.exists('/tmp/')#work for both file and directory

How to create directory:

import os
dir = os.path.dirname('/tmp/current_object/')
  if not os.path.exists(d):
    os.makedirs(d)

Using code above will ensure you did not create directory that already exists

How to delete file or directory:

import os
os.remove('/tmp/')

or if you want to delete non empty directory:

import shutil
shutil.rmtree('/tmp/somefolder')

How to create temporary directory:

import os
import tempfile
import shutil
#let OS decide where they want to create the temp directory
tmpdir = tempfile.mkdtemp('somesuffix', 'someprefix')
#You want to take control where you want the temp directory be created
tmpdir = tempfile.mkdtemp('somesuffix', 'someprefix', '/tmp/path/of/your/choice/')
#be sure to remove the temp directory once work is done
shutil.rmtree('/tmp/somefolder')

How to create temporary file:

import os
import tempfile
#let OS decide where they want to create the temp directory
tmpfile = tempfile.mkstemp('somesuffix', 'someprefix', None, 'some initial contents')
#You want to take control where you want the temp directory be created
tmpfile = tempfile.mkstemp('somesuffix', 'someprefix', '/tmp/path/of/your/choice/', 'some initial contents')
#be sure to remove the temp directory once work is done
os.remove(tmpfile)

How to check file permission:

import os
import stat
file = '/tmp/'
stt = os.stat(file)
mode = stt[stat.ST_MODE]
print "%s mode is: %s" % (file, mode)

Share

PHPSH: Test PHP Snippet, The Python Way!

If you know python, maybe you know the interactive python shell, too. If you don’t know both, well, let me explain it. Python has it’s built in interactive shell. When you install python and you execute the command, python, you will be introduced to a shell like interface where you could type python statements and have it evaluated and shown the result, right away. This is really convenience for learning purpose, or some simple snippet testing.

Continue reading “PHPSH: Test PHP Snippet, The Python Way!”

Share