本文整理汇总了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
示例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()在路径处理上很有用
示例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
示例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
示例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())
示例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)
示例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()
示例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
示例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)
示例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)
示例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'
示例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)
示例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
示例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)))