madscatt / zazmol

Library for defining molecular objects to create simulation and analysis programs To install: python setup.py install dependencies: numpy, mocker
GNU General Public License v3.0
0 stars 2 forks source link

use `with open` for dcd files #46

Closed StevenCHowell closed 1 year ago

StevenCHowell commented 7 years ago

When opening a file, the [recommended method]() is to use with open because it prevents forgetting to close files.

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

If not it would be worth considering adding this functionality to sassie.

The current method is not intuitive

dcd_file = mol.open_dcd_read(dcd_fname)

n_frames = dcd_file[2]
n_atoms = mol.natoms()

dist = np.zeros([n_frames, n_atoms, n_atoms])
for i in xrange(n_frames):
    mol.read_dcd_step(dcd_file, i)
    # do stuff

mol.close_dcd_read(dcd_file[0])
madscatt commented 7 years ago

No, the open_dcd_read method calls a C-method (via python) to grab a file pointer and header information and thus it is not applicable to use with open() ...

StevenCHowell commented 7 years ago

What I meant was could you use something like,

with mol.open_dcd_read(dcd_fname) as dcd_file:
    n_frames = dcd_file[2]
    n_atoms = mol.natoms()

    dist = np.zeros([n_frames, n_atoms, n_atoms])
    for i in xrange(n_frames):
        mol.read_dcd_step(dcd_file, i)
        # do stuff

One benefit is that it automatically would close the file at the end of the with statement (presumably by calling mol.close_dcd_read). Also, by eliminating the need to directly call close_dcd_read, it avoids the issue #44 raises.

madscatt commented 1 year ago

Where strictly python calls are used with open() is now used.