In [1]:
import os

In [2]:
print os.name


posix

In [3]:
type(os.name)


Out[3]:
str

In [4]:
os.environ


Out[4]:
{'MODULE_VERSION': '3.2.10', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/pvh', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', 'UPSTART_EVENTS': 'started starting', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'QT_IM_MODULE': 'ibus', 'LOGNAME': 'pvh', 'USER': 'pvh', 'GNOME_KEYRING_CONTROL': '/run/user/1000/keyring-XaaeKG', 'XDG_VTNR': '7', 'PATH': '/home/pvh/anaconda/bin:/home/pvh/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/pvh/Documents/eclipse_cl/bin/x86_64_linux:/home/pvh/Documents/pycharm-community-3.1.1/bin:/usr/local/cuda-6.0/bin:/home/pvh/.rvm/bin:/home/pvh/.rvm/bin', 'VIRTUALENVWRAPPER_SCRIPT': '/usr/share/virtualenvwrapper/virtualenvwrapper.sh', 'LD_LIBRARY_PATH': ':/usr/local/cuda-6.0/lib64', 'LANG': 'en_ZA.UTF-8', 'TERM': 'xterm-color', 'SHELL': '/bin/bash', 'XDG_SESSION_PATH': '/org/freedesktop/DisplayManager/Session0', 'XAUTHORITY': '/home/pvh/.Xauthority', 'LANGUAGE': 'en_ZA:en', 'DEFAULTS_PATH': '/usr/share/gconf/ubuntu.default.path', 'SHLVL': '1', 'QT_QPA_PLATFORMTHEME': 'appmenu-qt5', 'JOB': 'gnome-session', 'DISPLAY': ':0', 'UPSTART_INSTANCE': '', 'COMPIZ_CONFIG_PROFILE': 'ubuntu', 'WINDOWID': '62914572', 'SESSIONTYPE': 'gnome-session', 'IM_CONFIG_PHASE': '1', '_VIRTUALENVWRAPPER_API': ' mkvirtualenv rmvirtualenv lsvirtualenv showvirtualenv workon add2virtualenv cdsitepackages cdvirtualenv lssitepackages toggleglobalsitepackages cpvirtualenv setvirtualenvproject mkproject cdproject mktmpenv', 'GPG_AGENT_INFO': '/run/user/1000/keyring-XaaeKG/gpg:0:1', 'HOME': '/home/pvh', 'MODULESHOME': '/usr/share/modules', 'CLUTTER_IM_MODULE': 'xim', 'SELINUX_INIT': 'YES', 'SSH_AUTH_SOCK': '/run/user/1000/keyring-XaaeKG/ssh', 'MODULE_VERSION_STACK': '3.2.10', 'XDG_RUNTIME_DIR': '/run/user/1000', 'GIT_PAGER': 'cat', 'CUDA_HOME': '/usr/local/cuda-6.0', 'COMP_WORDBREAKS': ' \t\n"\'><;|&(:', 'GTK_MODULES': 'overlay-scrollbar:unity-gtk-module', 'VTE_VERSION': '3409', 'GDMSESSION': 'ubuntu', 'XMODIFIERS': '@im=ibus', 'UPSTART_JOB': 'unity-settings-daemon', 'TEXTDOMAINDIR': '/usr/share/locale/', 'QT4_IM_MODULE': 'ibus', 'XDG_DATA_DIRS': '/usr/share/ubuntu:/usr/share/gnome:/usr/local/share/:/usr/share/', 'XDG_SEAT_PATH': '/org/freedesktop/DisplayManager/Seat0', 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg', 'XDG_CURRENT_DESKTOP': 'Unity', 'XDG_SESSION_ID': 'c4', 'DBUS_SESSION_BUS_ADDRESS': 'unix:abstract=/tmp/dbus-sVOO7ljfR1', '_': '/home/pvh/anaconda/bin/ipython', 'MODULEPATH': '/etc/environment-modules/modules:/usr/share/modules/versions:/usr/Modules/$MODULE_VERSION/modulefiles:/usr/share/modules/modulefiles', 'GTK_IM_MODULE': 'ibus', 'DESKTOP_SESSION': 'ubuntu', 'UPSTART_SESSION': 'unix:abstract=/com/ubuntu/upstart-session/1000/3755', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'GNOME_KEYRING_PID': '3753', 'OLDPWD': '/home/pvh', 'LOADEDMODULES': '', 'GDM_LANG': 'en_US', 'NODE_PATH': '/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript', 'MANDATORY_PATH': '/usr/share/gconf/ubuntu.mandatory.path', 'INSTANCE': 'Unity', 'PWD': '/home/pvh/Documents/python', 'COLORTERM': 'gnome-terminal', 'TEXTDOMAIN': 'im-config', 'CLICOLOR': '1', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:', 'PAGER': 'cat', 'XDG_SEAT': 'seat0'}

In [5]:
print os.environ['PATH']


/home/pvh/anaconda/bin:/home/pvh/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/pvh/Documents/eclipse_cl/bin/x86_64_linux:/home/pvh/Documents/pycharm-community-3.1.1/bin:/usr/local/cuda-6.0/bin:/home/pvh/.rvm/bin:/home/pvh/.rvm/bin

In [6]:
print os.environ['HOME']


/home/pvh

In [7]:
print os.environ['LOGNAME']


pvh

In [8]:
print os.getcwd()


/home/pvh/Documents/python

In [9]:
os.chdir('..')

In [10]:
print os.getcwd()


/home/pvh/Documents

In [17]:
os.chdir('/home/pvh/Documents/python')

In [18]:
os.listdir('.')


Out[18]:
['README.md',
 'Untitled1.ipynb',
 'SimpleExercises.ipynb',
 'filtered_tb.gff',
 'Week1Exercises.ipynb',
 'PythonDictionaries.ipynb',
 'Loops.ipynb',
 'myfile4.txt',
 '.ipynb_checkpoints',
 'Functions.ipynb',
 'myfile2.txt',
 'NC_002549.faa',
 'myfile3.txt',
 'python.fasta',
 'bin',
 'tb.gff',
 'Untitled0.ipynb',
 'lib',
 '.git',
 'Dictionaries.ipynb',
 'Untitled2.ipynb',
 'Split, join, startswith, endswith.ipynb',
 'myfile.txt',
 'os module temp.ipynb',
 'os_module.ipynb',
 'Untitled6.ipynb',
 'NC_021054.gff',
 'LICENSE',
 'Conditionals.ipynb',
 'String Formatting.ipynb',
 'HelloWorld.ipynb',
 'Files.ipynb',
 'Sets.ipynb',
 'Compute.ipynb',
 'Writing files.ipynb',
 'Lists.ipynb',
 'NC_002549.gff',
 'Untitled4.ipynb',
 'Untitled5.ipynb',
 'Untitled3.ipynb']

In [19]:
os.mkdir('somedir')

In [21]:
sorted(os.listdir('.'))


Out[21]:
['.git',
 '.ipynb_checkpoints',
 'Compute.ipynb',
 'Conditionals.ipynb',
 'Dictionaries.ipynb',
 'Files.ipynb',
 'Functions.ipynb',
 'HelloWorld.ipynb',
 'LICENSE',
 'Lists.ipynb',
 'Loops.ipynb',
 'NC_002549.faa',
 'NC_002549.gff',
 'NC_021054.gff',
 'PythonDictionaries.ipynb',
 'README.md',
 'Sets.ipynb',
 'SimpleExercises.ipynb',
 'Split, join, startswith, endswith.ipynb',
 'String Formatting.ipynb',
 'Untitled0.ipynb',
 'Untitled1.ipynb',
 'Untitled2.ipynb',
 'Untitled3.ipynb',
 'Untitled4.ipynb',
 'Untitled5.ipynb',
 'Untitled6.ipynb',
 'Week1Exercises.ipynb',
 'Writing files.ipynb',
 'bin',
 'filtered_tb.gff',
 'lib',
 'myfile.txt',
 'myfile2.txt',
 'myfile3.txt',
 'myfile4.txt',
 'os module temp.ipynb',
 'os_module.ipynb',
 'python.fasta',
 'somedir',
 'tb.gff']

In [22]:
os.rmdir('somedir')

In [23]:
sorted(os.listdir('.'))


Out[23]:
['.git',
 '.ipynb_checkpoints',
 'Compute.ipynb',
 'Conditionals.ipynb',
 'Dictionaries.ipynb',
 'Files.ipynb',
 'Functions.ipynb',
 'HelloWorld.ipynb',
 'LICENSE',
 'Lists.ipynb',
 'Loops.ipynb',
 'NC_002549.faa',
 'NC_002549.gff',
 'NC_021054.gff',
 'PythonDictionaries.ipynb',
 'README.md',
 'Sets.ipynb',
 'SimpleExercises.ipynb',
 'Split, join, startswith, endswith.ipynb',
 'String Formatting.ipynb',
 'Untitled0.ipynb',
 'Untitled1.ipynb',
 'Untitled2.ipynb',
 'Untitled3.ipynb',
 'Untitled4.ipynb',
 'Untitled5.ipynb',
 'Untitled6.ipynb',
 'Week1Exercises.ipynb',
 'Writing files.ipynb',
 'bin',
 'filtered_tb.gff',
 'lib',
 'myfile.txt',
 'myfile2.txt',
 'myfile3.txt',
 'myfile4.txt',
 'os module temp.ipynb',
 'os_module.ipynb',
 'python.fasta',
 'tb.gff']

In [26]:
os.makedirs('somedir/otherdir')

In [28]:
os.removedirs('somedir/otherdir')

In [27]:
os.removedirs('somedir')


---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-27-8ac43d6da6cc> in <module>()
----> 1 os.removedirs('somedir')

/home/pvh/anaconda/lib/python2.7/os.pyc in removedirs(name)
    168 
    169     """
--> 170     rmdir(name)
    171     head, tail = path.split(name)
    172     if not tail:

OSError: [Errno 39] Directory not empty: 'somedir'

In [29]:
output_file = open('myjunk.txt', 'w')
output_file.close()

In [30]:
os.remove('myjunk.txt')

In [32]:
sorted(os.listdir('.'))


Out[32]:
['.git',
 '.ipynb_checkpoints',
 'Compute.ipynb',
 'Conditionals.ipynb',
 'Dictionaries.ipynb',
 'Files.ipynb',
 'Functions.ipynb',
 'HelloWorld.ipynb',
 'LICENSE',
 'Lists.ipynb',
 'Loops.ipynb',
 'NC_002549.faa',
 'NC_002549.gff',
 'NC_021054.gff',
 'PythonDictionaries.ipynb',
 'README.md',
 'Sets.ipynb',
 'SimpleExercises.ipynb',
 'Split, join, startswith, endswith.ipynb',
 'String Formatting.ipynb',
 'Untitled0.ipynb',
 'Untitled1.ipynb',
 'Untitled2.ipynb',
 'Untitled3.ipynb',
 'Untitled4.ipynb',
 'Untitled5.ipynb',
 'Untitled6.ipynb',
 'Week1Exercises.ipynb',
 'Writing files.ipynb',
 'bin',
 'filtered_tb.gff',
 'lib',
 'myfile.txt',
 'myfile2.txt',
 'myfile3.txt',
 'myfile4.txt',
 'os module temp.ipynb',
 'os_module.ipynb',
 'python.fasta',
 'tb.gff']

In [33]:
input_file = open('pthon.fasta')


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-33-3eb522b79042> in <module>()
----> 1 input_file = open('pthon.fasta')

IOError: [Errno 2] No such file or directory: 'pthon.fasta'

In [44]:
import sys
filename = 'python.fasta'
try:
    input_file = open(filename)
    result = 5 / 0
except IOError:
    print >>sys.stderr, "I can't open", filename
print "Now the program continues"


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-44-c6162b6a1a13> in <module>()
      3 try:
      4     input_file = open(filename)
----> 5     result = 5 / 0
      6 except IOError:
      7     print >>sys.stderr, "I can't open", filename

ZeroDivisionError: integer division or modulo by zero

In [46]:
import sys
filename = 'pthon.fasta'
try:
    input_file = open(filename)
    result = 5 / 0
except IOError:
    print >>sys.stderr, "I can't open", filename
except ZeroDivisionError:
    print >>sys.stderr, "You can't divide by zero"
print "Now the program continues"


Now the program continues
I can't open pthon.fasta

In [48]:
import sys

try:
    for filename in os.listdir('.'):
        input_file = open(filename)
        print "open worked fine for", filename
except IOError:
    print >>sys.stderr, "Failed to open:", filename


open worked fine for README.md
open worked fine for Untitled1.ipynb
open worked fine for SimpleExercises.ipynb
open worked fine for filtered_tb.gff
open worked fine for Week1Exercises.ipynb
open worked fine for PythonDictionaries.ipynb
open worked fine for Loops.ipynb
open worked fine for myfile4.txt
Failed to open: .ipynb_checkpoints

In [50]:
import sys

for filename in os.listdir('.'):
    try:
        input_file = open(filename)
        print "open worked fine for", filename
    except IOError:
        print >>sys.stderr, "Failed to open:", filename


open worked fine for README.md
open worked fine for Untitled1.ipynb
open worked fine for SimpleExercises.ipynb
open worked fine for filtered_tb.gff
open worked fine for Week1Exercises.ipynb
open worked fine for PythonDictionaries.ipynb
open worked fine for Loops.ipynb
open worked fine for myfile4.txt
open worked fine for Functions.ipynb
open worked fine for myfile2.txt
open worked fine for NC_002549.faa
open worked fine for myfile3.txt
open worked fine for python.fasta
open worked fine for tb.gff
open worked fine for Untitled0.ipynb
open worked fine for Dictionaries.ipynb
open worked fine for Untitled2.ipynb
open worked fine for Split, join, startswith, endswith.ipynb
open worked fine for myfile.txt
open worked fine for os module temp.ipynb
open worked fine for os_module.ipynb
open worked fine for Untitled6.ipynb
open worked fine for NC_021054.gff
open worked fine for LICENSE
open worked fine for Conditionals.ipynb
open worked fine for String Formatting.ipynb
open worked fine for HelloWorld.ipynb
open worked fine for Files.ipynb
open worked fine for Sets.ipynb
open worked fine for Compute.ipynb
open worked fine for Writing files.ipynb
open worked fine for Lists.ipynb
open worked fine for NC_002549.gff
open worked fine for Untitled4.ipynb
open worked fine for Untitled5.ipynb
open worked fine for Untitled3.ipynb
Failed to open: .ipynb_checkpoints
Failed to open: bin
Failed to open: lib
Failed to open: .git

In [57]:
import sys

for filename in os.listdir('.'):
    try:
        input_file = open(filename)
        #print "open worked fine for", filename
    except IOError as error:
        print >>sys.stderr, "Failed to open {}: {}".format(filename, error.strerror)
        print >>sys.stderr, "Error number:", error.errno
        print >>sys.stderr, "Error message:", error.strerror


Failed to open .ipynb_checkpoints: Is a directory
Error number: 21
Error message: Is a directory
Failed to open bin: Is a directory
Error number: 21
Error message: Is a directory
Failed to open tb.gff: Permission denied
Error number: 13
Error message: Permission denied
Failed to open lib: Is a directory
Error number: 21
Error message: Is a directory
Failed to open .git: Is a directory
Error number: 21
Error message: Is a directory

In [58]:
import sys

filename = 'python.fasta'
try:
    input_file = open(filename)
except IOError as e:
    print >>sys.stderr, "Failed to open {}: {}".format(filename, e.strerror)
else:
    count = 0
    for line in input_file:
        count += 1
    print "{} lines in {}".format(count, filename)


1103 lines in python.fasta

In [60]:
import sys

def count_lines(input_file):
    count = 0
    for line in filename:
        count += 1
    return count

for filename in sorted(os.listdir('.')):
    try:
        input_file = open(filename)
    except IOError as e:
        print >>sys.stderr, "Failed to open file {}: {}".format(filename, e.strerror)
    else:
        line_count = count_lines(input_file)
        print filename, line_count


Compute.ipynb 13
Conditionals.ipynb 18
Dictionaries.ipynb 18
Files.ipynb 11
Functions.ipynb 15
HelloWorld.ipynb 16
LICENSE 7
Lists.ipynb 11
Loops.ipynb 11
NC_002549.faa 13
NC_002549.gff 13
NC_021054.gff 13
PythonDictionaries.ipynb 24
README.md 9
Sets.ipynb 10
SimpleExercises.ipynb 21
Split, join, startswith, endswith.ipynb 39
String Formatting.ipynb 23
Untitled0.ipynb 15
Untitled1.ipynb 15
Untitled2.ipynb 15
Untitled3.ipynb 15
Untitled4.ipynb 15
Untitled5.ipynb 15
Untitled6.ipynb 15
Week1Exercises.ipynb 20
Writing files.ipynb 19
filtered_tb.gff 15
myfile.txt 10
myfile2.txt 11
myfile3.txt 11
myfile4.txt 11
os module temp.ipynb 20
os_module.ipynb 15
python.fasta 12
Failed to open file .git: Is a directory
Failed to open file .ipynb_checkpoints: Is a directory
Failed to open file bin: Is a directory
Failed to open file lib: Is a directory
Failed to open file tb.gff: Permission denied

In [63]:
filename = 'myjunk.txt'
with open(filename, 'w') as output_file:
    output_file.write('Happy Monday!\n')
    print "output file:", output_file
print "and now:", output_file


output file: <open file 'myjunk.txt', mode 'w' at 0x7f829edbb420>
and now: <closed file 'myjunk.txt', mode 'w' at 0x7f829edbb420>

In [62]:
filename = 'myjunk.txt'
output_file = open(filename, 'w')
with output_file:
    output_file.write('Happy Monday!\n')
    print "now:", output_file
print "and now:", output_file


now: <open file 'myjunk.txt', mode 'w' at 0x7f829edbb390>
and now: <closed file 'myjunk.txt', mode 'w' at 0x7f829edbb390>

In [64]:
import os.path

filename = '/home/pvh/Documents/python/myjunk.txt'
print os.path.basename(filename)
print os.path.dirname(filename)
print os.path.split(filename)


myjunk.txt
/home/pvh/Documents/python
('/home/pvh/Documents/python', 'myjunk.txt')

In [65]:
filename = '~/Documents/python/myjunk.txt'
print os.path.expanduser(filename)


/home/pvh/Documents/python/myjunk.txt

In [71]:
import os.path

bindir = os.path.expanduser('~/bin')
print "Listing:", bindir
os.chdir(bindir)
for filename in sorted(os.listdir(bindir)):
    if os.path.isfile(filename):
        print filename, "is a file"
    elif os.path.isdir(filename):
        print filename, "is a directory"


Listing: /home/pvh/bin
compute_it.py is a file
compute_it_v1.py is a file
count_seqs.py is a file
et is a file
etded is a file
faToTwoBit is a file
filter_gff.py is a file
gnome_to_mpris.py is a file
goodbye.py is a file
gooddata.sh is a file
greet.txt is a file
hello.py is a file
keep_eduroam_up.sh is a file
miranda is a file
output is a file
stats.sh is a file
sum.sh is a file
wc-working.py is a file
wc.py is a file
wc.py~ is a file
writer.py is a file
x86_64 is a directory
youtube-dl is a file

In [79]:
import os.path

bindir = os.path.expanduser('~/bin')
print "Listing:", bindir
print "Working directory:", os.getcwd()
for filename in sorted(os.listdir(bindir)):
    full_path = os.path.join(bindir, filename)
    print "filename:", filename, "full path:", full_path
    if os.path.isfile(filename):
        print filename, "is a file"
    elif os.path.isdir(filename):
        print filename, "is a directory"


Listing: /home/pvh/bin
Working directory: /home/pvh/Documents/python
filename: compute_it.py full path: /home/pvh/bin/compute_it.py
filename: compute_it_v1.py full path: /home/pvh/bin/compute_it_v1.py
filename: count_seqs.py full path: /home/pvh/bin/count_seqs.py
filename: et full path: /home/pvh/bin/et
filename: etded full path: /home/pvh/bin/etded
filename: faToTwoBit full path: /home/pvh/bin/faToTwoBit
filename: filter_gff.py full path: /home/pvh/bin/filter_gff.py
filename: gnome_to_mpris.py full path: /home/pvh/bin/gnome_to_mpris.py
filename: goodbye.py full path: /home/pvh/bin/goodbye.py
filename: gooddata.sh full path: /home/pvh/bin/gooddata.sh
filename: greet.txt full path: /home/pvh/bin/greet.txt
filename: hello.py full path: /home/pvh/bin/hello.py
filename: keep_eduroam_up.sh full path: /home/pvh/bin/keep_eduroam_up.sh
filename: miranda full path: /home/pvh/bin/miranda
filename: output full path: /home/pvh/bin/output
filename: stats.sh full path: /home/pvh/bin/stats.sh
filename: sum.sh full path: /home/pvh/bin/sum.sh
filename: wc-working.py full path: /home/pvh/bin/wc-working.py
filename: wc.py full path: /home/pvh/bin/wc.py
filename: wc.py~ full path: /home/pvh/bin/wc.py~
filename: writer.py full path: /home/pvh/bin/writer.py
filename: x86_64 full path: /home/pvh/bin/x86_64
filename: youtube-dl full path: /home/pvh/bin/youtube-dl

In [ ]: