A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Basic Python: Filenames and paths

Another Python post! I am still learning the language. Since I cannot remember everything, I am posting it here for future reference.

Get the Current Working Directory
To get the “current working directory” do this:

import os
current_dir = os.getcwd()
print current_dir

If you are doing this from the command line, you should see something like:


Get the Absolute Path of a File

import os
abs_path = os.path.abspath('myfile.txt')
print abs_path #will show something like: /home/wenbert/myfile.txt

Check if a File or Directory Exists
I am demonstrating this as if you are in the interactive Python shell and not as a file.

>>> import os
>>> os.path.exists('myfile.txt')
>>> os.path.exists('non-existent-file.txt')

Check “value” if it is a Directory or is a File

>>> import os
>>> os.path.isdir('myfile.txt')
>>> os.path.isdir('/home/wenbert/mydirectory')


>>> import os
>>> os.path.isfile('myfile.txt')
>>> os.path.isfile('/home/wenbert/mydirectory')

List everything inside a directory

>>> import os
>>> os.listdir('/home/wenbert/mydirectory')
['sub_directory','myfile.txt', 'sample.txt']

FYI: I am reading “Learn Pythong the Hard Way” and “Think Python”.

Comments / Suggestions are welcomed!

This entry was posted in General and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>