Skip to content
dstoeckel edited this page Mar 16, 2015 · 3 revisions

Using the MolFileFactory

If you just want to open a molecule regardless of the file type, (meaning you do not need to work around filesystem specific quirks.) you can use the MolFileFactory class in order to open arbitrary filetypes:

C++

#include <BALL/KERNEL/system.h>
#include <BALL/FORMAT/molFileFactory.h>
#include <BALL/FORMAT/genericMolFile.h>

using namespace BALL;

GenericMolFile* infile = MolFileFactory::open(filename);

if (!infile) 
{
  std::cerr << "Could not determine filetype, aborting" << std::endl;
  exit(-1);
}

if (!*infile) 
{
  std::cerr << "Invalid file, aborting" << std::endl;
  exit(-1);
}

System system;
*infile >> system;

// Important: Cleanup
infile->close();
delete infile;

/*
 * Do something in between here
 */

// NOTE: specifying an open mode does only work with BALL > 1.2
GenericMolFile* outfile = MolFileFactory::open(outname, std::ios::out);

if (!outfile) 
{
  std::cerr << "Could not determine filetype, aborting" << std::endl;
  exit(-1);
}

if (!*outfile) 
{
  std::cerr << "Invalid file, aborting" << std::endl;
  exit(-1);
}

*outfile << system;

// Important: Cleanup
outfile->close();
delete outfile;

Python

Remark: This code only works for BALL 1.4 or later

from BALL import *

infile = MolFileFactory.open(filename);

if not infile:
  print "Could not determine filetype, aborting"
  exit(-1)

system = System()
infile.read(system)

#Close the file after reading
infile.close()

#
# Do something in between here
#

# NOTE: specifying an open mode does only work with BALL > 1.2
outfile = MolFileFactory.open(outname, OpenMode(File.MODE_OUT))

if not outfile:
  print "Could not determine filetype, aborting"
  exit(-1)

outfile.write(system)

# Important: Cleanup
outfile.close()
Clone this wiki locally