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:
/home/wenbert
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') True >>> os.path.exists('non-existent-file.txt') False |
Check “value” if it is a Directory or is a File
isdir()
>>> import os >>> os.path.isdir('myfile.txt') False >>> os.path.isdir('/home/wenbert/mydirectory') True |
isfile()
>>> import os >>> os.path.isfile('myfile.txt') True >>> os.path.isfile('/home/wenbert/mydirectory') False |
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!