当前位置: 首页>>代码示例>>Python>>正文


Python os.rename方法代码示例

本文整理汇总了Python中os.rename方法的典型用法代码示例。如果您正苦于以下问题:Python os.rename方法的具体用法?Python os.rename怎么用?Python os.rename使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os的用法示例。


在下文中一共展示了os.rename方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: atomic_writer

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def atomic_writer(fpath, mode):
    """Atomic file writer.

    .. versionadded:: 1.12

    Context manager that ensures the file is only written if the write
    succeeds. The data is first written to a temporary file.

    :param fpath: path of file to write to.
    :type fpath: ``unicode``
    :param mode: sames as for :func:`open`
    :type mode: string

    """
    suffix = '.{}.tmp'.format(os.getpid())
    temppath = fpath + suffix
    with open(temppath, mode) as fp:
        try:
            yield fp
            os.rename(temppath, fpath)
        finally:
            try:
                os.remove(temppath)
            except (OSError, IOError):
                pass 
开发者ID:TKkk-iOSer,项目名称:wechat-alfred-workflow,代码行数:27,代码来源:util.py

示例2: munge

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def munge(src_dir):
    # stored as: ./MCG-COCO-val2014-boxes/COCO_val2014_000000193401.mat
    # want:      ./MCG/mat/COCO_val2014_0/COCO_val2014_000000141/COCO_val2014_000000141334.mat

    files = os.listdir(src_dir)
    for fn in files:
        base, ext = os.path.splitext(fn)
        # first 14 chars / first 22 chars / all chars + .mat
        # COCO_val2014_0/COCO_val2014_000000447/COCO_val2014_000000447991.mat
        first = base[:14]
        second = base[:22]
        dst_dir = os.path.join('MCG', 'mat', first, second)
        if not os.path.exists(dst_dir):
            os.makedirs(dst_dir)
        src = os.path.join(src_dir, fn)
        dst = os.path.join(dst_dir, fn)
        print 'MV: {} -> {}'.format(src, dst)
        os.rename(src, dst) 
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:20,代码来源:mcg_munge.py

示例3: change_name

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def change_name(path):
    global i
    if not os.path.isdir(path) and not os.path.isfile(path):
        return False
    if os.path.isfile(path):
        file_path = os.path.split(path)  # 分割出目录与文件
        lists = file_path[1].split('.')  # 分割出文件与文件扩展名
        file_ext = lists[-1]  # 取出后缀名(列表切片操作)
        img_ext = ['bmp', 'jpeg', 'gif', 'psd', 'png', 'jpg']
        if file_ext in img_ext:
            os.rename(path, file_path[0] + '/' + lists[0] + '_fc.' + file_ext)
            i += 1  # 注意这里的i是一个陷阱
        # 或者
        # img_ext = 'bmp|jpeg|gif|psd|png|jpg'
        # if file_ext in img_ext:
        #    print('ok---'+file_ext)
    elif os.path.isdir(path):
        for x in os.listdir(path):
            change_name(os.path.join(path, x))  # os.path.join()在路径处理上很有用 
开发者ID:matiji66,项目名称:face-attendance-machine,代码行数:21,代码来源:rename_file.py

示例4: _rename_over_existing

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def _rename_over_existing(src, dest):
    try:
        # On Windows, this will throw EEXIST, on Linux it won't.
        os.rename(src, dest)
    except IOError as err:
        if err.errno == errno.EEXIST:
            # Clearly this song-and-dance is not in fact atomic,
            # but if something goes wrong putting the new file in
            # place at least the backup file might still be
            # around.
            backup = "{0}.bak-{1}".format(dest, str(uuid.uuid4()))
            os.rename(dest, backup)
            try:
                os.rename(src, dest)
            except Exception as err:
                os.rename(backup, dest)
                raise err
            finally:
                try:
                    os.remove(backup)
                except Exception as err:
                    pass 
开发者ID:ContinuumIO,项目名称:ciocheck,代码行数:24,代码来源:utils.py

示例5: download_figshare

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def download_figshare(file_name, file_ext, dir_path='./', change_name = None):
    prepare_data_dir(dir_path)
    url = 'https://ndownloader.figshare.com/files/' + file_name
    wget.download(url, out=dir_path)
    file_path = os.path.join(dir_path, file_name)

    if file_ext == '.zip':
        zip_ref = zipfile.ZipFile(file_path,'r')
        if change_name is not None:
            dir_path = os.path.join(dir_path, change_name)
        zip_ref.extractall(dir_path)
        zip_ref.close()
        os.remove(file_path)
    elif file_ext == '.tar.bz2':
        tar_ref = tarfile.open(file_path,'r:bz2')
        if change_name is not None:
            dir_path = os.path.join(dir_path, change_name)
        tar_ref.extractall(dir_path)
        tar_ref.close()
        os.remove(file_path)
    elif change_name is not None:
        os.rename(file_path, os.path.join(dir_path, change_name))

# Download QM9 dataset 
开发者ID:priba,项目名称:nmp_qc,代码行数:26,代码来源:download.py

示例6: updateData

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def updateData(settings, type):
    """
        Updates data in a folder, the existing folder is renamed.
    """
    print('%s preparation started!' % settings.getDataDescription())

    if not os.path.exists(settings.getLocalDst(type)):
        print("The destination directory '%s' doesn't exist." % settings.getLocalDst(type))
        return
    fileName = settings.getFileName(type)
    downloadFile(fileName, settings, type)

    dirName = os.path.join(settings.getLocalDst(type), fileName.rsplit('.', 2)[0])
    if os.path.isdir(dirName):
        newDirName = str(dirName + '_' + str(time.time()).split('.')[0])
        try:
            os.rename(dirName, newDirName)
            print("Directory '%s' already exists, it will be renamed to '%s'" % (dirName, newDirName))
        except Exception:
            print("Can't rename directory '%s', this directory will be overwritten." % dirName)
    decompress(fileName, settings, type)
    dirName = ".".join(fileName.split('.')[:-2])
    verifyChecksumForDir(dirName, settings, type)
    print("%s are ready to use!" % settings.getDataDescription()) 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:26,代码来源:update.py

示例7: create_gsa_mapping

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def create_gsa_mapping(path, metadata, sample_name, shuffle):
    """
    Creates the binning gold standard/gsa mapping
    """
    to_genome = name_to_genome(metadata)
    gsa_path = os.path.join(path, "anonymous_gsa.fasta") #
    count = 0
    if not os.path.exists(gsa_path):
        gsa_path = os.path.join(path, "anonymous_gsa.fasta.gz") # if zipped
        with gzip.open(gsa_path,'r') as gsa:
            for line in gsa:
                if line.startswith('>'):
                    count += 1
        with gzip.open(gsa_path,'r') as gsa:
            gsa_temp = shuffle_anonymize(gsa, path, to_genome, metadata, sample_name, count, shuffle)
    else:
        with open(gsa_path,'r') as gsa:
            for line in gsa:
                if line.startswith('>'):
                    count += 1
        with open(gsa_path,'r') as gsa:
            gsa_temp = shuffle_anonymize(gsa, path, to_genome, metadata, sample_name, count, shuffle)
    os.rename(gsa_temp, gsa_path) 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:25,代码来源:create_joint_gs.py

示例8: pack

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def pack(self) -> None:
        """
        Pack all files in zip
        """

        def rm_file(file: str):
            if os.path.exists(file) and os.path.isfile(file):
                os.remove(file)

        def rename_file(file: str):
            target = file + ".old"
            rm_file(target)
            if os.path.exists(file) and os.path.isfile(file):
                os.rename(file, target)

        self._check_files([self._weights_file, self._state_file])

        rename_file(self._checkpoint_file)
        with ZipFile(self._checkpoint_file, 'w') as zipfile:
            zipfile.write(self._weights_file, os.path.basename(self._weights_file))
            zipfile.write(self._state_file, os.path.basename(self._state_file))
            zipfile.write(self._trainer_file, os.path.basename(self._trainer_file))

        self.clear_files() 
开发者ID:toodef,项目名称:neural-pipeline,代码行数:26,代码来源:fsm.py

示例9: get_cifar10

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def get_cifar10(data_dir):
    if not os.path.isdir(data_dir):
        os.system("mkdir " + data_dir)
    cwd = os.path.abspath(os.getcwd())
    os.chdir(data_dir)
    if (not os.path.exists('train.rec')) or \
       (not os.path.exists('test.rec')) :
        import urllib, zipfile, glob
        dirname = os.getcwd()
        zippath = os.path.join(dirname, "cifar10.zip")
        urllib.urlretrieve("http://data.mxnet.io/mxnet/data/cifar10.zip", zippath)
        zf = zipfile.ZipFile(zippath, "r")
        zf.extractall()
        zf.close()
        os.remove(zippath)
        for f in glob.glob(os.path.join(dirname, "cifar", "*")):
            name = f.split(os.path.sep)[-1]
            os.rename(f, os.path.join(dirname, name))
        os.rmdir(os.path.join(dirname, "cifar"))
    os.chdir(cwd)

# data 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:24,代码来源:get_data.py

示例10: checkNewVMs

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def checkNewVMs(vmDomains):
    newVMNames = []
    vmMetaDataFilePath = os.path.join(homePath, dataDirectory + "totalVMs.json")
    for vmDomain in vmDomains:
        newVMNames.append(vmDomain.name())
    if os.path.isfile(vmMetaDataFilePath) == False:
        towritePreviousVM = {}
        towritePreviousVM["allVM"] = newVMNames
        with open(vmMetaDataFilePath, 'w') as vmMetaDataFile:
            json.dump(towritePreviousVM, vmMetaDataFile)
    else:
        with open(vmMetaDataFilePath, 'r') as vmMetaDataFile:
            oldVMDomains = json.load(vmMetaDataFile)["allVM"]
        if cmp(newVMNames, oldVMDomains) != 0:
            towritePreviousVM = {}
            towritePreviousVM["allVM"] = newVMNames
            with open(vmMetaDataFilePath, 'w') as vmMetaDataFile:
                json.dump(towritePreviousVM, vmMetaDataFile)
            if os.path.isfile(os.path.join(homePath, dataDirectory + date + ".csv")) == True:
                oldFile = os.path.join(homePath, dataDirectory + date + ".csv")
                newFile = os.path.join(homePath, dataDirectory + date + "." + time.strftime("%Y%m%d%H%M%S") + ".csv")
                os.rename(oldFile, newFile) 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:24,代码来源:getmetrics_kvm.py

示例11: checkNewInstances

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def checkNewInstances(instances):
    newInstances = []
    currentDate = time.strftime("%Y%m%d")
    instancesMetaDataFilePath = os.path.join(homePath, dataDirectory + "totalVMs.json")
    for instance in instances:
        newInstances.append(instance[1])
    if os.path.isfile(instancesMetaDataFilePath) == False:
        towritePreviousInstances = {}
        towritePreviousInstances["allInstances"] = newInstances
        with open(instancesMetaDataFilePath, 'w') as instancesMetaDataFile:
            json.dump(towritePreviousInstances, instancesMetaDataFile)
    else:
        with open(instancesMetaDataFilePath, 'r') as instancesMetaDataFile:
            oldInstances = json.load(instancesMetaDataFile)["allInstances"]
        if cmp(newInstances, oldInstances) != 0:
            towritePreviousInstances = {}
            towritePreviousInstances["allInstances"] = newInstances
            with open(instancesMetaDataFilePath, 'w') as instancesMetaDataFile:
                json.dump(towritePreviousInstances, instancesMetaDataFile)
            if os.path.isfile(os.path.join(homePath, dataDirectory + currentDate + ".csv")) == True:
                oldFile = os.path.join(homePath, dataDirectory + currentDate + ".csv")
                newFile = os.path.join(homePath,
                                       dataDirectory + currentDate + "." + time.strftime("%Y%m%d%H%M%S") + ".csv")
                os.rename(oldFile, newFile) 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:26,代码来源:getmetrics_jolokia.py

示例12: check_output_is_expected

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def check_output_is_expected(directory, capsys):
    """Create, move, and delete a file."""
    # Create file
    original_filename = os.path.join(directory, 'file.txt')
    pathlib.Path(original_filename).touch()
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File created!\n'
    # Move file
    new_filename = os.path.join(directory, 'new_filename.txt')
    os.rename(original_filename, new_filename)
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File moved!\n'
    # Delete file
    os.remove(new_filename)
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File deleted!\n' 
开发者ID:biesnecker,项目名称:hachiko,代码行数:21,代码来源:test_hachiko.py

示例13: _rename_atomic

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def _rename_atomic(src, dst):
            ta = _CreateTransaction(None, 0, 0, 0, 0, 1000, 'Werkzeug rename')
            if ta == -1:
                return False
            try:
                retry = 0
                rv = False
                while not rv and retry < 100:
                    rv = _MoveFileTransacted(src, dst, None, None,
                                             _MOVEFILE_REPLACE_EXISTING |
                                             _MOVEFILE_WRITE_THROUGH, ta)
                    if rv:
                        rv = _CommitTransaction(ta)
                        break
                    else:
                        time.sleep(0.001)
                        retry += 1
                return rv
            finally:
                _CloseHandle(ta) 
开发者ID:jojoin,项目名称:cutout,代码行数:22,代码来源:posixemulation.py

示例14: rename

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
开发者ID:jojoin,项目名称:cutout,代码行数:19,代码来源:posixemulation.py

示例15: Move

# 需要导入模块: import os [as 别名]
# 或者: from os import rename [as 别名]
def Move(src: Text, dst: Text):
  """Move a file from src to dst.

  Python's os.rename doesn't support overwrite on Windows.

  Args:
    src: The full file path to the source.
    dst: The full file path to the destination.

  Raises:
    Error: Failure moving the file.
  """
  try:
    Remove(dst)
    os.rename(src, dst)
  except OSError as e:
    raise Error('Failure moving file from %s to %s. (%s)' % (src, dst, str(e))) 
开发者ID:google,项目名称:glazier,代码行数:19,代码来源:file_util.py


注:本文中的os.rename方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。