Returns a local File that the user can write output to.  The caller
provides both the eventual FS target name and the local working
file.  If the FS is local, we write directly into the target.  If
the FS is remote, we write into the tmp local area.
544053
public Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile)
    throws IOException {
    return fs.startLocalOutput(fsOutputFile, tmpLocalFile);
  }
1031730
def gettextfile(remotefile, localfile = File.basename(remotefile)) # :yield: line
      result = nil
      if localfile
        f = open(localfile, "w")
      elsif !block_given?
        result = ""
      end
      begin
	retrlines("RETR " + remotefile) do |line|
	  f.puts(line) if localfile
	  yield(line) if block_given?
          result.concat(line + "\n") if result
	end
        return result
      ensure
	f.close if localfile
      end
    end
100304
def cache_local_file(self, path, **kwargs):
        '''
        
        '''
        dest = os.path.join(self.opts['cachedir'], 'localfiles',
                            path.lstrip('/'))
        destdir = os.path.dirname(dest)

        if not os.path.isdir(destdir):
            os.makedirs(destdir)

        shutil.copyfile(path, dest)
        return dest
1086967
def copy_to_local(self, src, localdest, **kwargs):
        
        with self.open(src, **kwargs) as fsrc:
            with io.open(localdest, 'wb') as fdst:
                shutil.copyfileobj(fsrc, fdst)
1279079
function write(myLocale) {
    try {
        stats = fs.lstatSync(directory);
    } catch(e) {
        fs.mkdirSync(directory, 0755);
    }
    fs.writeFile(locate(myLocale), JSON.stringify(locales[myLocale], null, "\t"));
}
814462
def download(self, localfile: str, remotefile: str, overwrite: bool = True, **kwargs):
      
      valid = self._sb.file_info(remotefile, quiet = True)

      if valid is None:
         return {'Success' : False, 
                 'LOG'     : "File "+str(remotefile)+" does not exist."}

      if valid == {}:
         return {'Success' : False, 
                 'LOG'     : "File "+str(remotefile)+" is a directory."}

      if os.path.isdir(localfile):
         locf = localfile + os.sep + remotefile.rpartition(self._sb.hostsep)[2]
      else:
         locf = localfile

      try:
         fd = open(locf, 'wb')
      except OSError as e:
         return {'Success' : False, 
                 'LOG'     : "File "+str(locf)+" could not be opened. Error was: "+str(e)}

      port =  kwargs.get('port', 0)

      if port==0 and self.sascfg.tunnel:
         # we are using a tunnel; default to that port
         port = self.sascfg.tunnel

      try:
         sock = socks.socket()
         if self.sascfg.tunnel:
            sock.bind(('localhost', port))
         else:
            sock.bind(('', port))
         port = sock.getsockname()[1]
      except OSError:
         return {'Success' : False, 
                 'LOG'     : "Error try to open a socket in the download method. Call failed."}

      if self.sascfg.ssh:
         if not self.sascfg.tunnel:
            host = self.sascfg.hostip #socks.gethostname()
         else:
            host = 'localhost'
      else:
         host = ''

      code = """
         filename saspydir '"""+remotefile+"""' recfm=F encoding=binary lrecl=4096;
         filename sock socket '"""+host+""":"""+str(port)+"""' recfm=S encoding=binary;
         data _null_;
         file sock;
         infile saspydir;
         input;
         put _infile_;
         run;\n"""

      sock.listen(1)
      self._asubmit(code, 'text')

      datar = b''

      newsock = (0,0)
      try:
         newsock = sock.accept()
         while True:
            data = newsock[0].recv(4096)

            if len(data):
               datar += data
            else:
               if len(datar):
                  fd.write(datar)
               break
            if len(datar) > 8300:
               fd.write(datar[:8192])
               datar = datar[8192:]
      except:
         if newsock[0]:
            newsock[0].shutdown(socks.SHUT_RDWR)
            newsock[0].close()
         sock.close()
         fd.close()
         ll = self.submit("filename saspydir;", 'text')
         return {'Success' : False, 
                 'LOG'     : "Download was interupted. Returning the SAS log:\n\n"+ll['LOG']}

      newsock[0].shutdown(socks.SHUT_RDWR)
      newsock[0].close()
      sock.close()

      fd.flush()
      fd.close()

      ll = self.submit("filename saspydir;", 'text')
      return {'Success' : True, 
              'LOG'     : ll['LOG']}
610934
def get(self, remote, local=None):
        
        if isinstance(local, file_type):  # open file, leave open
            local_file = local
        elif local is None:  # return string
            local_file = buffer_type()
        else:  # path to file, open, write/close return None
            local_file = open(local, 'wb')

        self.conn.retrbinary("RETR %s" % remote, local_file.write)

        if isinstance(local, file_type):
            pass
        elif local is None:
            contents = local_file.getvalue()
            local_file.close()
            return contents
        else:
            local_file.close()

        return None
487936
def write_file(writeFunc, index, existing, x):
    
    # Toil fileStore reference
    if x.startswith("toilfs:"):
        return x
    # File literal outputs with no path, we don't write these and will fail
    # with unsupportedRequirement when retrieving later with getFile
    elif x.startswith("_:"):
        return x
    else:
        x = existing.get(x, x)
        if x not in index:
            if not urlparse.urlparse(x).scheme:
                rp = os.path.realpath(x)
            else:
                rp = x
            try:
                index[x] = "toilfs:" + writeFunc(rp)
                existing[index[x]] = x
            except Exception as e:
                cwllogger.error("Got exception '%s' while copying '%s'", e, x)
                raise
        return index[x]
790477
private FileOutputStream fos() throws IOException {
        if (closed)
            throw new IOException("Output stream is already closed");
        if (os == null || currFileBytesWritten >= partSize) {
            if (os != null) {
                os.close();
                // notify about the new file ready for processing
                observer.onPartCreate(new PartCreationEvent(
                        getFile(filesCreated), filesCreated, false, this));
            }
            currFileBytesWritten = 0;
            filesCreated++;
            blockIfNecessary();
            final File file = getFile(filesCreated);
            os = new FileOutputStream(file);
        }
        return os;
    }
1067216
def write_to_file(file_path, data, mkdir=False):
    
    folder, fname = os.path.split(file_path)
    return write_to_file_by_name(folder, fname, data, mkdir)
307454
def write(file = find_file, force: false, format: :auto)
      if file && ::File.exist?(file)
        if !force
          raise WriteError, "File `#{file}` already exists. " \
                            'Use :force option to overwrite.'
        elsif !::File.writable?(file)
          raise WriteError, "Cannot write to #{file}."
        end
      end

      if file.nil?
        dir = @location_paths.empty? ? Dir.pwd : @location_paths.first
        file = ::File.join(dir, "#{filename}#{@extname}")
      end

      content = marshal(file, @settings, format: format)
      ::File.write(file, content)
    end
1198316
public static LocalFileSystem getLocal(Configuration conf)
    throws IOException {
    return (LocalFileSystem)get(LocalFileSystem.NAME, conf);
  }
466584
private AFTPClient actionPutFile() throws IOException, PageException {
	required("remotefile", remotefile);
	required("localfile", localfile);

	AFTPClient client = getClient();
	Resource local = ResourceUtil.toResourceExisting(pageContext, localfile);// new File(localfile);
	// if(failifexists && local.exists()) throw new ApplicationException("File ["+local+"] already
	// exist, if you want to overwrite, set attribute
	// failIfExists to false");
	InputStream is = null;

	try {
	    is = IOUtil.toBufferedInputStream(local.getInputStream());
	    client.setFileType(getType(local));
	    client.storeFile(remotefile, is);
	}
	finally {
	    IOUtil.closeEL(is);
	}
	writeCfftp(client);

	return client;
    }
44350
def write_file(self, target_path, html):
        
        logger.debug("Building to {}{}".format(self.fs_name, target_path))
        with self.fs.open(smart_text(target_path), 'wb') as outfile:
            outfile.write(six.binary_type(html))
            outfile.close()
1320589
function write(description, options, callback) {
  var file = vfile(description)

  // Weird, right? Otherwise `fs` doesn’t accept it.
  if (!callback && typeof options === 'function') {
    callback = options
    options = undefined
  }

  if (!callback) {
    return new Promise(executor)
  }

  executor(resolve, callback)

  function resolve(result) {
    callback(null, result)
  }

  function executor(resolve, reject) {
    var fp

    try {
      fp = path.resolve(file.cwd, file.path)
    } catch (error) {
      return reject(error)
    }

    fs.writeFile(fp, file.contents || '', options, done)

    function done(error) {
      if (error) {
        reject(error)
      } else {
        resolve()
      }
    }
  }
}
1356767
def upload(self, local_fn, remote_fn=None, dont_overwrite=False):
    """"""

    # support wildcard through glob
    if '*' in local_fn:
      for local_subfn in glob.glob(local_fn):
        self.upload(local_subfn)
      return

    if remote_fn is None:
      remote_fn = os.path.basename(local_fn)

    if dont_overwrite and self.exists(remote_fn):
      self.log("Remote file %s exists, skipping" % (remote_fn,))
      return

    if not remote_fn.startswith('/'):
      remote_fn = self.taskdir + '/' + remote_fn

    remote_fn = remote_fn.replace('~', self.homedir)
    self.log('uploading ' + local_fn + ' to ' + remote_fn)

    local_fn = os.path.abspath(local_fn)
    self._run_raw("cp -R %s %s" % (local_fn, remote_fn))
199376
def copy_file_to_remote(self, local_path, remote_path):
        
        sftp_client = self.transport.open_sftp_client()
        LOG.debug('Copy the local file to remote. '
                  'Source=%(src)s. Target=%(target)s.' %
                  {'src': local_path, 'target': remote_path})
        try:
            sftp_client.put(local_path, remote_path)
        except Exception as ex:
            LOG.error('Failed to copy the local file to remote. '
                      'Reason: %s.' % six.text_type(ex))
            raise SFtpExecutionError(err=ex)