Convenience function: Detect file extension and write via Atomistica or ASE.
    Has support for writing LAMMPS data files.
491778
def write(fn, a, **kwargs):
    
    ext = fn[fn.rfind('.'):].split('@')
    if ext[0] == '.out' or ext[0] == '.dat':
        return write_atoms(fn, a)
    elif ext[0] == '.lammps':
        return write_lammps_data(fn, a, velocities=True, **kwargs)
    elif ext[0] == '.nc':
        return NetCDFTrajectory(fn, 'w').write(a)
    else:
        return ase.io.write(fn, a, **kwargs)
828120
function(done) {
          readBuffer(info.filePath, function(data) {
            lzma.compress(data, 1, function(result, error) {
              if (error) {
                throw error;
              }
              writeBuffer(info.lzFilePath, new Buffer(result), function() {
                info.lzTime = Date.now();
                // Open and read the size of the minified+lzma output
                readSize(info.lzFilePath, function(size) {
                  info.lzSize = size;
                  done();
                });
              });
            });
          });
        }
782249
private static void writeFile(CyclicBarrier barrier, AtomicLong runtime, int count,
      AlluxioConfiguration alluxioConf)
      throws Exception {
    FileSystem fileSystem = FileSystem.Factory.create(alluxioConf);
    byte[] buffer = new byte[(int) Math.min(sFileSize, 4 * Constants.MB)];
    Arrays.fill(buffer, (byte) 'a');
    AlluxioURI path = filename(count);

    if (fileSystem.exists(path)) {
      fileSystem.delete(path);
    }

    barrier.await();
    long startTime = System.nanoTime();
    long bytesWritten = 0;
    try (FileOutStream outStream = fileSystem.createFile(path)) {
      while (bytesWritten < sFileSize) {
        outStream.write(buffer, 0, (int) Math.min(buffer.length, sFileSize - bytesWritten));
        bytesWritten += buffer.length;
      }
    }
    runtime.addAndGet(System.nanoTime() - startTime);
  }
1205180
async function fsinfo(format){

    // try to establish a connection to the module
    await getConnection();

    const {metadata, files} = await _nodeMcuConnector.fsinfo();

    // json output - third party applications
    if (format == 'json') {
        writeOutput(JSON.stringify({
            files: files,
            meta: metadata
        }));

    // raw format - suitable for use in bash scripts
    }else if (format == 'raw'){
        // print fileinfo
        files.forEach(function(file){
            writeOutput(file.name);
        });

    }else{
        _mculogger.log('Free Disk Space: ' + metadata.remaining + ' KB | Total: ' + metadata.total + ' KB | ' + files.length + ' Files');

        // files found ?
        if (files.length==0){
            _mculogger.log('No Files found - have you created the file-system?');
        }else{
            _mculogger.log('Files stored into Flash (SPIFFS)');

            // print fileinfo
            files.forEach(function(file){
                _mculogger.log(' - ' + file.name + ' (' + file.size + ' Bytes)');
            });
        }
    }
}
332488
def write(self, filename, arcname=None, compress_type=None):
        """"""
        if not self.fp:
            raise RuntimeError(
                  "Attempt to write to ZIP archive that was already closed")

        st = os.stat(filename)
        isdir = stat.S_ISDIR(st.st_mode)
        mtime = time.localtime(st.st_mtime)
        date_time = mtime[0:6]
        # Create ZipInfo instance to store file information
        if arcname is None:
            arcname = filename
        arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
        while arcname[0] in (os.sep, os.altsep):
            arcname = arcname[1:]
        if isdir:
            arcname += '/'
        zinfo = ZipInfo(arcname, date_time)
        zinfo.external_attr = (st[0] & 0xFFFF) << 16L      # Unix attributes
        if compress_type is None:
            zinfo.compress_type = self.compression
        else:
            zinfo.compress_type = compress_type

        zinfo.file_size = st.st_size
        zinfo.flag_bits = 0x00
        zinfo.header_offset = self.fp.tell()    # Start of header bytes

        self._writecheck(zinfo)
        self._didModify = True

        if isdir:
            zinfo.file_size = 0
            zinfo.compress_size = 0
            zinfo.CRC = 0
            self.filelist.append(zinfo)
            self.NameToInfo[zinfo.filename] = zinfo
            self.fp.write(zinfo.FileHeader())
            return

        fp = open(filename, "rb")
        # Must overwrite CRC and sizes with correct data later
        zinfo.CRC = CRC = 0
        zinfo.compress_size = compress_size = 0
        zinfo.file_size = file_size = 0
        self.fp.write(zinfo.FileHeader())
        if zinfo.compress_type == ZIP_DEFLATED:
            cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
                 zlib.DEFLATED, -15)
        else:
            cmpr = None
        while 1:
            buf = fp.read(1024 * 8)
            if not buf:
                break
            file_size = file_size + len(buf)
            CRC = crc32(buf, CRC) & 0xffffffff
            if cmpr:
                buf = cmpr.compress(buf)
                compress_size = compress_size + len(buf)
            self.fp.write(buf)
        fp.close()
        if cmpr:
            buf = cmpr.flush()
            compress_size = compress_size + len(buf)
            self.fp.write(buf)
            zinfo.compress_size = compress_size
        else:
            zinfo.compress_size = file_size
        zinfo.CRC = CRC
        zinfo.file_size = file_size
        # Seek backwards and write CRC and file sizes
        position = self.fp.tell()       # Preserve current position in file
        self.fp.seek(zinfo.header_offset + 14, 0)
        self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size,
              zinfo.file_size))
        self.fp.seek(position, 0)
        self.filelist.append(zinfo)
        self.NameToInfo[zinfo.filename] = zinfo
39486
function hasFileType(file, fileExt) {
  file = path.basename(file);
  var ext = path.extname(file);
  do {
    if (ext === fileExt) {
      return true;
    } else {
      file = path.basename(file, ext);
      ext = path.extname(file);
    }
  } while (ext);
  return false;
}
72831
def write(self, session, directory, name, maskMap):
        

        # Assemble Path to file
        name_split = name.split('.')
        name = name_split[0]

        # Default extension
        extension = ''

        if len(name_split) >= 2:
            extension = name_split[-1]

        # Run name preprocessor method if present
        try:
            name = self._namePreprocessor(name)
        except:
            'DO NOTHING'

        if extension == '':
            filename = '{0}.{1}'.format(name, self.fileExtension)
        else:
            filename = '{0}.{1}'.format(name, extension)

        filePath = os.path.join(directory, filename)

        with open(filePath, 'w') as openFile:
            # Write Lines
            self._write(session=session,
                        openFile=openFile,
                        maskMap=maskMap)
1262478
function fileExtension(name, defaultValue) {
        if (defaultValue === void 0) { defaultValue = ""; }
        var extension = defaultValue;
        if (name) {
            var idx = name.lastIndexOf(".");
            if (idx > 0) {
                extension = name.substring(idx + 1, name.length).toLowerCase();
            }
        }
        return extension;
    }
1189123
function _getExtension(file) {
        var ret;
        if (file) {
            var fileTypes = file.split(".");
            var len = fileTypes.length;
            if (0 === len) {
                return ret;
            }
            ret = fileTypes[len - 1];
            return ret;
        }
    }
825298
def detect_format(filename):
    
    filename = Path(filename)

    if filename.is_dir():
        if list(filename.glob('*.stc')) and list(filename.glob('*.erd')):
            return Ktlx
        elif (filename / 'patient.info').exists():
            return Moberg
        elif (filename / 'info.xml').exists():
            return EgiMff
        elif list(filename.glob('*.openephys')):
            return OpenEphys
        elif list(filename.glob('*.txt')):
            return Text
        else:
            raise UnrecognizedFormat('Unrecognized format for directory ' +
                                     str(filename))
    else:
        if filename.suffix == '.won':
            return Wonambi

        if filename.suffix.lower() == '.trc':
            return Micromed

        if filename.suffix == '.set':
            return EEGLAB

        if filename.suffix == '.edf':
            return Edf

        if filename.suffix == '.abf':
            return Abf

        if filename.suffix == '.vhdr' or filename.suffix == '.eeg':
            return BrainVision

        if filename.suffix == '.dat':  # very general
            try:
                _read_header_length(filename)

            except (AttributeError, ValueError):  # there is no HeaderLen
                pass

            else:
                return BCI2000

        with filename.open('rb') as f:
            file_header = f.read(8)
            if file_header in (b'NEURALCD', b'NEURALSG', b'NEURALEV'):
                return BlackRock
            elif file_header[:6] == b'MATLAB':  # we might need to read more
                return FieldTrip
        
        if filename.suffix.lower() == '.txt':
            with filename.open('rt') as f:
                first_line = f.readline()
                if '.rr' in first_line[-4:]:
                    return LyonRRI
        
        else:
            raise UnrecognizedFormat('Unrecognized format for file ' +
                                     str(filename))
816383
public static String fileExtensionForMIMEType(String mimeType) {
        loadMappings();

        String ext = mimeTypeToExtensionMap.get(mimeType);

        if (ext == null) ext = "dat";

        return ext;
    }
172076
void writePositiveExtensionInt(int extensionType, int reference) throws IOException {
        if (reference < 0) {
            throw new IllegalArgumentException("Can only serialize positive references: " + reference);
        }
        if (reference < 0xFF) {
            output.write(FIX_EXT_1);
            output.write(extensionType);
            output.writeByte((byte) reference);
        } else if (reference < 0xFFFF) {
            output.writeByte(FIX_EXT_2);
            output.write(extensionType);
            output.writeShort((short) reference);
        } else {
            output.writeByte(FIX_EXT_4);
            output.write(extensionType);
            output.writeInt(reference);
        }
    }
414568
def format_from_extension(self, extension):
        """"""
        formats = [name
                   for name, format in self._formats.items()
                   if format.get('file_extension', None) == extension]
        if len(formats) == 0:
            return None
        elif len(formats) == 2:
            raise RuntimeError("Several extensions are registered with "
                               "that extension; please specify the format "
                               "explicitly.")
        else:
            return formats[0]
1112063
def WriteFileHeader(self, arcname=None, compress_type=None, st=None):
    """"""

    if not self._stream:
      raise ArchiveAlreadyClosedError(
          "Attempting to write to a ZIP archive that was already closed.")

    self.cur_zinfo = self._GenerateZipInfo(
        arcname=arcname, compress_type=compress_type, st=st)
    self.cur_file_size = 0
    self.cur_compress_size = 0

    if self.cur_zinfo.compress_type == zipfile.ZIP_DEFLATED:
      self.cur_cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
                                       zlib.DEFLATED, -15)
    else:
      self.cur_cmpr = None

    self.cur_crc = 0

    if not self._stream:
      raise ArchiveAlreadyClosedError(
          "Attempting to write to a ZIP archive that was already closed.")

    self.cur_zinfo.header_offset = self._stream.tell()
    # Call _writeCheck(self.cur_zinfo) to do sanity checking on zinfo structure
    # that we've constructed.
    self._zip_fd._writecheck(self.cur_zinfo)  # pylint: disable=protected-access
    # Mark ZipFile as dirty. We have to keep self._zip_fd's internal state
    # coherent so that it behaves correctly when close() is called.
    self._zip_fd._didModify = True  # pylint: disable=protected-access

    # Write FileHeader now. It's incomplete, but CRC and uncompressed/compressed
    # sized will be written later in data descriptor.
    self._stream.write(self.cur_zinfo.FileHeader())

    return self._stream.GetValueAndReset()
765380
function(file, cb) {
                if (!file) return cb();

                readExtension(file, function(err, ext) {
                    // ignore errors from extension check
                    //if (err) console.error(err);

                    ext = ext || extname;

                    switch (ext.toLowerCase()) {
                    // Unzip and symlink to directory.
                    case '.zip':
                        if (nosymlink) {
                            unzip(file, function(err, file) {
                                if (err) return cb(err);
                                l.Datasource.file = file;
                                return cb();
                            });
                        } else {
                            unzip(file, function(err, file_found) {
                                if (err) return cb(err);
                                l.Datasource.file = path.join(base,
                                                      'layers',
                                                      name,
                                                      path.basename(file_found));
                                return utils.processFiles(file_found,
                                                        l.Datasource.file,
                                                        file_linking_method,
                                                        {cache:cache}, cb);
                            });
                        }
                        break;
                    case '.shp':
                        if (nosymlink) {
                            l.Datasource.file = file;
                            return cb();
                        } else {
                            l.Datasource.file =
                                path.join(base, 'layers', name, path.basename(file));
                            return utils.processFiles(file, l.Datasource.file, file_linking_method, {cache:cache}, cb);
                        }
                        break;
                    default:
                        if (nosymlink) {
                            l.Datasource.file = file;
                            return cb();
                        } else {
                            l.Datasource.file =
                                path.join(base, 'layers', name + ext);
                            return file_linking_method(file, l.Datasource.file, {cache:cache}, cb);
                        }
                        break;
                    }
                });
            }
673652
def GenericPump(filenames, use_jppy=False, name="GenericPump", **kwargs):
    """"""
    if isinstance(filenames, str):
        filenames = [filenames]

    try:
        iter(filenames)
    except TypeError:
        log.critical("Don't know how to iterate through filenames.")
        raise TypeError("Invalid filenames.")

    extensions = set(os.path.splitext(fn)[1] for fn in filenames)

    if len(extensions) > 1:
        log.critical("Mixed filetypes, please use only files of the same type")
        raise IOError("Mixed filetypes.")

    extension = list(extensions)[0]

    io = {
        '.evt': EvtPump,
        '.h5': HDF5Pump,
        '.root': EventPump if use_jppy else AanetPump,
        '.dat': DAQPump,
        '.dqd': CLBPump,
    }

    if extension not in io:
        log.critical(
            "No pump found for file extension '{0}'".format(extension)
        )
        raise ValueError("Unknown filetype")

    missing_files = [fn for fn in filenames if not os.path.exists(fn)]
    if missing_files:
        if len(missing_files) == len(filenames):
            message = "None of the given files could be found."
            log.critical(message)
            raise SystemExit(message)
        else:
            log.warning(
                "The following files are missing and ignored: {}".format(
                    ', '.join(missing_files)
                )
            )

    input_files = set(filenames) - set(missing_files)

    if len(input_files) == 1:
        return io[extension](filename=filenames[0], name=name, **kwargs)
    else:
        return io[extension](filenames=filenames, name=name, **kwargs)
1043818
def WriteFileChunk(self, chunk):
    """"""
    precondition.AssertType(chunk, bytes)

    if not self._stream:
      raise ArchiveAlreadyClosedError(
          "Attempting to write to a ZIP archive that was already closed.")

    self.cur_file_size += len(chunk)
    # TODO(user):pytype: crc32 is not visible outside of zipfile.
    # pytype: disable=module-attr
    self.cur_crc = zipfile.crc32(chunk, self.cur_crc) & 0xffffffff
    # pytype: enable=module-attr

    if self.cur_cmpr:
      chunk = self.cur_cmpr.compress(chunk)
      self.cur_compress_size += len(chunk)

    self._stream.write(chunk)
    return self._stream.GetValueAndReset()