*Thread-safe* renames file to temporary filename. Returns new name
196364
def rename_to_temp(filename):
    """"""
    with _rename_to_temp_lock:
        root, ext = os.path.splitext(filename)
        if len(ext) > 0:
            ext = ext[1:]  # the dot (".") is originally included
        new_name = new_filename(root, ext)
        os.rename(filename, new_name)
        return new_name
1350847
def rename_file(self, old_save_name, new_save_name, new_path):
        
        if old_save_name in self._files:
            del self._files[old_save_name]
        self.update_file(new_save_name, new_path)
1141890
def replace_in_file(self, file_path, old_exp, new_exp):
        
        self.term.print_info(u"Making replacement into {}"
                                 .format(self.term.text_in_color(file_path,
                                                                 TERM_GREEN)))
        # write the new version into a temporary file
        tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
        for filelineno, line in enumerate(io.open(file_path, encoding="utf-8")):
            if old_exp in line:
                line = line.replace(old_exp, new_exp)
            try:
                tmp_file.write(line.encode('utf-8'))
            except TypeError:
                tmp_file.write(line)

        name = tmp_file.name # keep the name
        tmp_file.close()
        shutil.copy(name, file_path) # replace the original one
        os.remove(name)
399991
def atomic_write(filename)
      dirname, basename = File.split(filename)
      basename = [
        basename,
        Thread.current.object_id,
        Process.pid,
        rand(1000000)
      ].join('.'.freeze)
      tmpname = File.join(dirname, basename)

      File.open(tmpname, 'wb+') do |f|
        yield f
      end

      File.rename(tmpname, filename)
    ensure
      File.delete(tmpname) if File.exist?(tmpname)
    end
510316
function renameFiles(files)
{
  files.forEach(function (file)
  {
    var originalName = path.basename(file);
    var newFileName = originalName.toLowerCase();
    var directory = path.dirname(file);
    if (originalName != newFileName)
    {
      fs.renameSync(file, directory + "/" + newFileName); //, function(err)

      if (debug)
        console.log('Renamed: %s --> %s', originalName, newFileName);

      originalFiles.push(originalName);
      renamedFiles.push(newFileName);
    }
  });
}
411068
def make_tmp_name(name):
    
    path, base = os.path.split(name)
    tmp_base = ".tmp-%s-%s" % (base, uuid4().hex)
    tmp_name = os.path.join(path, tmp_base)

    try:
        yield tmp_name
    finally:
        safe_remove(tmp_name)
177231
def get_connection_filename(filename, tmp_path = None, replace_file = False, verbose = False):
	
	def mktmp(path, suffix = ".sqlite", verbose = False):
		with temporary_files_lock:
			# make sure the clean-up signal traps are installed
			install_signal_trap()
			# create the remporary file and replace it's
			# unlink() function
			temporary_file = tempfile.NamedTemporaryFile(suffix = suffix, dir = path if path != "_CONDOR_SCRATCH_DIR" else os.getenv("_CONDOR_SCRATCH_DIR"))
			def new_unlink(self, orig_unlink = temporary_file.unlink):
				# also remove a -journal partner, ignore all errors
				try:
					orig_unlink("%s-journal" % self)
				except:
					pass
				orig_unlink(self)
			temporary_file.unlink = new_unlink
			filename = temporary_file.name
			# hang onto reference to prevent its removal
			temporary_files[filename] = temporary_file
		if verbose:
			print >>sys.stderr, "using '%s' as workspace" % filename
		# mkstemp() ignores umask, creates all files accessible
		# only by owner;  we should respect umask.  note that
		# os.umask() sets it, too, so we have to set it back after
		# we know what it is
		umsk = os.umask(0777)
		os.umask(umsk)
		os.chmod(filename, 0666 & ~umsk)
		return filename

	def truncate(filename, verbose = False):
		if verbose:
			print >>sys.stderr, "'%s' exists, truncating ..." % filename,
		try:
			fd = os.open(filename, os.O_WRONLY | os.O_TRUNC)
		except Exception as e:
			if verbose:
				print >>sys.stderr, "cannot truncate '%s': %s" % (filename, str(e))
			return
		os.close(fd)
		if verbose:
			print >>sys.stderr, "done."

	def cpy(srcname, dstname, verbose = False):
		if verbose:
			print >>sys.stderr, "copying '%s' to '%s' ..." % (srcname, dstname),
		shutil.copy2(srcname, dstname)
		if verbose:
			print >>sys.stderr, "done."
		try:
			# try to preserve permission bits.  according to
			# the documentation, copy() and copy2() are
			# supposed preserve them but don't.  maybe they
			# don't preserve them if the destination file
			# already exists?
			shutil.copystat(srcname, dstname)
		except Exception as e:
			if verbose:
				print >>sys.stderr, "warning: ignoring failure to copy permission bits from '%s' to '%s': %s" % (filename, target, str(e))

	database_exists = os.access(filename, os.F_OK)

	if tmp_path is not None:
		# for suffix, can't use splitext() because it only keeps
		# the last bit, e.g. won't give ".xml.gz" but just ".gz"
		target = mktmp(tmp_path, suffix = ".".join(os.path.split(filename)[-1].split(".")[1:]), verbose = verbose)
		if database_exists:
			if replace_file:
				# truncate database so that if this job
				# fails the user won't think the database
				# file is valid
				truncate(filename, verbose = verbose)
			else:
				# need to copy existing database to work
				# space for modifications
				i = 1
				while True:
					try:
						cpy(filename, target, verbose = verbose)
					except IOError as e:
						import errno
						import time
						if e.errno not in (errno.EPERM, errno.ENOSPC):
							# anything other
							# than out-of-space
							# is a real error
							raise
						if i < 5:
							if verbose:
								print >>sys.stderr, "warning: attempt %d: %s, sleeping and trying again ..." % (i, errno.errorcode[e.errno])
							time.sleep(10)
							i += 1
							continue
						if verbose:
							print >>sys.stderr, "warning: attempt %d: %s: working with original file '%s'" % (i, errno.errorcode[e.errno], filename)
						with temporary_files_lock:
							del temporary_files[target]
						target = filename
					break
	else:
		with temporary_files_lock:
			if filename in temporary_files:
				raise ValueError("file '%s' appears to be in use already as a temporary database file and is to be deleted" % filename)
		target = filename
		if database_exists and replace_file:
			truncate(target, verbose = verbose)

	del mktmp
	del truncate
	del cpy

	return target
1148964
def rename_to_tmp_name(self):
        
        self.client.rename(
            self.id,
            '%s_%s' % (self.short_id, self.name)
        )
1185657
def replace_file_or_dir(dest, source):
    
    from rez.vendor.atomicwrites import replace_atomic

    if not os.path.exists(dest):
        try:
            os.rename(source, dest)
            return
        except:
            if not os.path.exists(dest):
                raise

    try:
        replace_atomic(source, dest)
        return
    except:
        pass

    with make_tmp_name(dest) as tmp_dest:
        os.rename(dest, tmp_dest)
        os.rename(source, dest)
317746
def fobj_to_tempfile(f, suffix=''):
    
    with tempfile.NamedTemporaryFile(
            dir=TEMPDIR, suffix=suffix, delete=False) as t:
        shutil.copyfileobj(f, t)
    try:
        yield t.name
    finally:
        os.remove(t.name)
140657
def tempfile_writer(target):
    ''''''
    tmp = target.parent / ('_%s' % target.name)
    try:
        with tmp.open('wb') as fd:
            yield fd
    except:
        tmp.unlink()
        raise
    LOG.debug('rename %s -> %s', tmp, target)
    tmp.rename(target)
436665
def rename_file(self, fmfile, newname):
        

        if not isinstance(fmfile, dict):
            raise FMBaseError('fmfile must be a <dict>')

        method, url = get_URL('file_rename')

        payload = {
            'apikey': self.config.get('apikey'),
            'logintoken': self.session.cookies.get('logintoken'),
            'fileid': fmfile.get('fileid'),
            'filename': newname
            }

        res = getattr(self.session, method)(url, params=payload)
        if res.status_code == 200:
            self._complete = True
            return True

        hellraiser(res)
905432
def safe_concurrent_rename(src, dst):
  
  # Delete dst, in case it existed (with old content) even before any concurrent processes
  # attempted this write. This ensures that at least one process writes the new content.
  if os.path.isdir(src):  # Note that dst may not exist, so we test for the type of src.
    safe_rmtree(dst)
  else:
    safe_delete(dst)
  try:
    shutil.move(src, dst)
  except IOError as e:
    if e.errno != errno.EEXIST:
      raise
405266
def rename_file(self, instance, field_name):
        
        file = getattr(instance, field_name)

        if file:
            new_name = get_hashed_filename(file.name, file)
            if new_name != file.name:
                print('    Renaming "%s" to "%s"' % (file.name, new_name))
                file.save(os.path.basename(new_name), file, save=False)
                return True

        return False
1233161
def cleanup(temp_name):
    '''  '''
    for filename in iglob(temp_name + '*' if temp_name else temp_name):
        try:
            os.remove(filename)
        except OSError:
            pass
1037473
def _rename_file(self, line=""):
        

        if not self.all_ontologies:
            self._help_nofiles()
        else:
            out = []
            for each in self.all_ontologies:
                if line in each:
                    out += [each]
            choice = self._selectFromList(out, line)
            if choice:
                fullpath = self.LOCAL_MODELS + "/" + choice
                print(fullpath)
                if os.path.isfile(fullpath):

                    self._print("--------------")
                    self._print("Please enter a new name for <%s>, including the extension (blank=abort)"
                                % choice)
                    var = input()
                    if var:
                        try:
                            os.rename(fullpath, self.LOCAL_MODELS + "/" + var)
                            manager.rename_pickled_ontology(choice, var)
                            self._print("<%s> was renamed succesfully." % choice)
                            self.all_ontologies = manager.get_localontologies()
                        except:
                            self._print("Not a valid name. An error occurred.")
                            return
                    else:
                        return

                else:
                    self._print("File not found.")
                # delete
                if self.current and self.current['fullpath'] == fullpath:
                    self.current = None
                    self.currentEntity = None
                    self.prompt = _get_prompt()

        return
597396
private static void renameTmpFile(FileSystem hdfs, String targetTmpPath, String tmpSuffix)
    {
        String basePath = extractBasePath(targetTmpPath, tmpSuffix);

        boolean isFileExists = true;

        try
        {
            isFileExists = hdfs.exists(new Path(basePath));
        }
        catch (IOException ioex)
        {
            String logFormat = "Failed to search target file exists. Skip file rename. : TargetUri={0}";
            String logMessage = MessageFormat.format(logFormat, basePath);
            logger.warn(logMessage, ioex);
            return;
        }

        if (isFileExists)
        {
            String logFormat = "File exists renamed target. Skip file rename. : BeforeUri={0} , AfterUri={1}";
            String logMessage = MessageFormat.format(logFormat, targetTmpPath, basePath);
            logger.warn(logMessage);
        }
        else
        {
            try
            {
                hdfs.rename(new Path(targetTmpPath), new Path(basePath));
            }
            catch (IOException ioex)
            {
                String logFormat = "Failed to HDFS file rename. Skip rename file and continue preprocess. : BeforeUri={0} , AfterUri={1}";
                String logMessage = MessageFormat.format(logFormat, targetTmpPath, basePath);
                logger.warn(logMessage, ioex);
            }
        }
    }