In [1]:
pwd


Out[1]:
u'/home/pvh/Desktop/python/data'

In [2]:
cd ../molecules/


/home/pvh/Desktop/python/molecules

In [3]:
pwd


Out[3]:
u'/home/pvh/Desktop/python/molecules'

In [4]:
ls


cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb

In [5]:
input_file = open('methane.pdb')

In [6]:
type(input_file)


Out[6]:
file

In [14]:
input_file = open('methane.pdb')
for line in input_file:
    line = line.rstrip()
    print line


COMPND      METHANE
AUTHOR      DAVE WOODCOCK  95 12 18
ATOM      1  C           1       0.257  -0.363   0.000  1.00  0.00
ATOM      2  H           1       0.257   0.727   0.000  1.00  0.00
ATOM      3  H           1       0.771  -0.727   0.890  1.00  0.00
ATOM      4  H           1       0.771  -0.727  -0.890  1.00  0.00
ATOM      5  H           1      -0.771  -0.727   0.000  1.00  0.00
TER       6              1
END

In [15]:
input_file = open('mehane.pdb')
for line in input_file:
    line = line.rstrip()
    print line


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-15-9703441e3a2f> in <module>()
----> 1 input_file = open('mehane.pdb')
      2 for line in input_file:
      3     line = line.rstrip()
      4     print line

IOError: [Errno 2] No such file or directory: 'mehane.pdb'

In [22]:
def print_file(filename):
    try:
        input_file = open(filename)
    except IOError as ex:
        print 'I got an error when opening', filename, ':', ex.strerror
    else:
        for line in input_file:
            line = line.rstrip()
            print line

In [24]:
filename = 'methane.pdb'
print_file(filename)


COMPND      METHANE
AUTHOR      DAVE WOODCOCK  95 12 18
ATOM      1  C           1       0.257  -0.363   0.000  1.00  0.00
ATOM      2  H           1       0.257   0.727   0.000  1.00  0.00
ATOM      3  H           1       0.771  -0.727   0.890  1.00  0.00
ATOM      4  H           1       0.771  -0.727  -0.890  1.00  0.00
ATOM      5  H           1      -0.771  -0.727   0.000  1.00  0.00
TER       6              1
END

In [28]:
def count_atom(filename, atom_type):
    try:
        input_file = open(filename)
    except IOError as ex:
        print 'I got an error when opening', filename, ':', ex.strerror
    else:
        atom_count = 0
        for line in input_file:
            line = line.rstrip()
            if line.startswith('ATOM'):
                fields = line.split()
                if fields[2] == atom_type:
                    atom_count = atom_count + 1
    return atom_count

In [30]:
count_atom('methane.pdb', 'C')


Out[30]:
1

In [ ]: