If filename exists, overwrite or modify it to be unique.
356193
def overwrite_file_check(args, filename):
    """"""
    if not args['overwrite'] and os.path.exists(filename):
        # Confirm overwriting of the file, or modify filename
        if args['no_overwrite']:
            overwrite = False
        else:
            try:
                overwrite = confirm_input(input('Overwrite {0}? (yes/no): '
                                                .format(filename)))
            except (KeyboardInterrupt, EOFError):
                sys.exit()
        if not overwrite:
            new_filename = modify_filename_id(filename)
            while os.path.exists(new_filename):
                new_filename = modify_filename_id(new_filename)
            return new_filename
    return filename
654963
def cleanupFilename(self, name):
        """"""

        context = self.context
        id = ''
        name = name.replace('\\', '/')  # Fixup Windows filenames
        name = name.split('/')[-1]  # Throw away any path part.
        for c in name:
            if c.isalnum() or c in '._':
                id += c

        # Raise condition here, but not a lot we can do about that
        if context.check_id(id) is None and getattr(context, id, None) is None:
            return id

        # Now make the id unique
        count = 1
        while 1:
            if count == 1:
                sc = ''
            else:
                sc = str(count)
            newid = "copy{0:s}_of_{1:s}".format(sc, id)
            if context.check_id(newid) is None \
                    and getattr(context, newid, None) is None:
                return newid
            count += 1
229773
def remove_if_exists(filename):
    
    try:
        os.unlink(filename)
    except OSError as ex:
        if ex.errno != errno.ENOENT:
            raise
926671
def update_safe(filename: str, **kw: Any) -> Generator[IO, None, None]:
    
    with tempfile.NamedTemporaryFile(
        dir=os.path.dirname(filename),
        delete=False,
        prefix=f"{os.path.basename(filename)}.",
        **kw,
    ) as tf:
        if os.path.exists(filename):
            os.chmod(tf.name, os.stat(filename).st_mode & 0o7777)
        tf.has_changed = False  # type: ignore
        yield tf
        if not os.path.exists(tf.name):
            return
        filename_tmp = tf.name
    if os.path.exists(filename) and filecmp.cmp(filename, filename_tmp, shallow=False):
        os.unlink(filename_tmp)
    else:
        os.rename(filename_tmp, filename)
        tf.has_changed = True
360615
def set_current_filename(self, filename, focus=True):
        """"""
        index = self.has_filename(filename)
        if index is not None:
            if focus:
                self.set_stack_index(index)
            editor = self.data[index].editor
            if focus:
                editor.setFocus()
            else:
                self.stack_history.remove_and_append(index)

            return editor
370141
def change_filename(filehandle, meta):
    
    filename = secure_filename(meta.get('filename', filehandle.filename))
    basename, _ = os.path.splitext(filename)
    meta['original_filename'] = filehandle.filename
    filehandle.filename = filename + '.jpg'
    return filehandle
601617
def modify_filename_id(filename):
    """"""
    split_filename = os.path.splitext(filename)
    id_num_re = re.compile('(\(\d\))')
    id_num = re.findall(id_num_re, split_filename[-2])
    if id_num:
        new_id_num = int(id_num[-1].lstrip('(').rstrip(')')) + 1

        # Reconstruct filename with incremented id and its extension
        filename = ''.join((re.sub(id_num_re, '({0})'.format(new_id_num),
                                   split_filename[-2]), split_filename[-1]))
    else:
        split_filename = os.path.splitext(filename)

        # Reconstruct filename with new id and its extension
        filename = ''.join(('{0} (2)'.format(split_filename[-2]),
                            split_filename[-1]))
    return filename
5408
def file_exists(filename):
    
    try:
        return os.path.isfile(filename)
    except (UnicodeDecodeError, UnicodeEncodeError, ValueError):
        return False
737741
private boolean renameOverwrite(String oldname, String newname) {

        boolean deleted = delete(newname);

        if (exists(oldname)) {
            File file = new File(oldname);

            return file.renameTo(new File(newname));
        }

        return deleted;
    }
677870
def getNonexistingFile(name):
    
    num = 1
    stem, ext = os.path.splitext(name)
    filename = name
    while os.path.exists(filename):
        suffix = "-%d" % num
        filename = stem + suffix + ext
        num += 1
    return filename
1109939
def ensure_dir(filename):
    """"""
    directory = os.path.dirname(filename)
    if directory and not os.path.isdir(directory):
        os.makedirs(directory)
67137
def on_exists(fname):
    # type: (str) -> None
    

    if os.path.isfile(fname):
        newfile = fname + ".old"
        print("{} -> {}".format(fname, newfile))
        os.rename(fname, newfile)
965814
public static function uniqueFilename($filename, $path) {
	
		// fixes path if not containing trailing slash
		self::fixTrailingSlash($path);
	
		if (file_exists($path . $filename)) {
			$dot  = strrpos($filename,'.');
			$ext  = substr($filename,$dot);
			$name = substr($filename,0,$dot);
			$hash = substr(md5(time()),0,6);
			$filename = $name . '-' . $hash . $ext;
		}
	
		return $filename;
	
	}
1335596
def create_file(self, name: str, generate_unique_name: bool = False):
        '''
        
        '''
        def enumerate_name():
            yield name
            index = 0
            while True:
                index += 1
                yield f'{name} ({index})'
        for n in enumerate_name():
            path = os.path.join(self._path, n)
            if os.path.exists(path):
                if not generate_unique_name:
                    raise FileExistsError
            return FileInfo(path)
953358
def _mkdir(newdir):
    
    if os.path.isdir(newdir):
        pass
    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)
    else:
        head, tail = os.path.split(newdir)
        if head and not os.path.isdir(head):
            _mkdir(head)
        if tail:
            os.mkdir(newdir)
411814
def is_file_exists(filename):
        # type: (AnyStr) -> bool
        """"""
        if filename is None or not os.path.exists(filename) or not os.path.isfile(filename):
            return False
        else:
            return True
1186451
def frame_unique(f):
        
        return f.f_code.co_filename, f.f_code.co_name, f.f_lineno