本文整理匯總了Python中shutil.copy方法的典型用法代碼示例。如果您正苦於以下問題:Python shutil.copy方法的具體用法?Python shutil.copy怎麽用?Python shutil.copy使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類shutil
的用法示例。
在下文中一共展示了shutil.copy方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: generateDatasetFiles
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def generateDatasetFiles(self):
with open(os.path.join(self.datasetPath,'frameAnnotations.csv')) as csvfile:
anotations_list = csvfile.readlines()
# print(anotations_list)
anotations_list.pop(0)
for sample in anotations_list:
sample = sample.split(';')
# print(sample)
self.labels.add(sample[1])
self.generateXML(file=sample[0],
label=sample[1],
_bndbox={
"xmin": sample[2],
"ymin": sample[3],
"xmax": sample[4],
"ymax": sample[5]})
shutil.copy(
os.path.join(self.datasetPath,sample[0]),
self.imgPath)
self.FileSequence.append(sample[0])
# break
示例2: open
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def open(self,database):
"""
params:
database: str. Database to be opered. The path should be included
"""
assert(database[-4:]=='.mdo')
if not os.path.exists(database):
self._create(database)
operate_db=database[:-4]+'.op'
shutil.copy(database,operate_db)
# engine=create_engine('sqlite:///:memory:')
engine=create_engine('sqlite:///'+operate_db) #should be run in memory in the future
Session=o.sessionmaker(bind=engine)
self.session=Session()
self.__operate_db=operate_db
self.__storage_db=database
示例3: copy_iso
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def copy_iso(src, dst):
"""
A simple wrapper for copying larger files. This is necessary as
shutil copy files is much slower under Windows platform
:param src: Path to source file
:param dst: Destination directory
:return:
"""
if platform.system() == "Windows":
# Note that xcopy asks if the target is a file or a directory when
# source filename (or dest filename) contains space(s) and the target
# does not exist.
assert os.path.exists(dst)
subprocess.call(['xcopy', '/Y', src, dst], shell=True)
elif platform.system() == "Linux":
shutil.copy(src, dst)
示例4: _prepare_simulation_subfolder
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def _prepare_simulation_subfolder(self, directory_strains):
"""
Create strain directory and copy templates and parameter file into it.
@param directory_strains: Directory for the simulated strains
@type directory_strains: str | unicode
@return: Nothing
@rtype: None
"""
if not os.path.exists(directory_strains):
os.mkdir(directory_strains)
for filename in self._directory_template_filenames:
src = os.path.join(self._directory_template, filename)
dst = os.path.join(directory_strains, filename)
shutil.copy(src, dst)
示例5: copy_dependencies
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def copy_dependencies(f):
config_path = '/etc/yangcatalog/yangcatalog.conf'
config = ConfigParser.ConfigParser()
config._interpolation = ConfigParser.ExtendedInterpolation()
config.read(config_path)
yang_models = config.get('Directory-Section', 'save-file-dir')
tmp = config.get('Directory-Section', 'temp')
out = f.getvalue()
letters = string.ascii_letters
suffix = ''.join(random.choice(letters) for i in range(8))
dep_dir = '{}/yangvalidator-dependencies-{}'.format(tmp, suffix)
os.mkdir(dep_dir)
dependencies = out.split(':')[1].strip().split(' ')
for dep in dependencies:
for file in glob.glob(r'{}/{}*.yang'.format(yang_models, dep)):
shutil.copy(file, dep_dir)
return dep_dir
示例6: __next__
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def __next__(self):
self.count += 1
img0 = self.imgs.copy()
if cv2.waitKey(1) == ord('q'): # q to quit
cv2.destroyAllWindows()
raise StopIteration
# Letterbox
img = [letterbox(x, new_shape=self.img_size, interp=cv2.INTER_LINEAR)[0] for x in img0]
# Stack
img = np.stack(img, 0)
# Normalize RGB
img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB
img = np.ascontiguousarray(img, dtype=np.float16 if self.half else np.float32) # uint8 to fp16/fp32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
return self.sources, img, img0, None
示例7: GetBuildPackages
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def GetBuildPackages(self):
"""Downloads the packages to be installed."""
package_path = os.path.join(self.cwd, BUILD, 'Packages/')
try:
os.mkdir(package_path)
except OSError:
pass
catalogs = [os.path.join(self.cwd, 'base%s_new.catalog' % self.os_version),
os.path.join(self.cwd,
'thirdparty%s_new.catalog' % self.os_version)]
for catalog in catalogs:
f = open(catalog, 'r')
packages = f.readlines()
for line in packages:
shutil.copy(os.path.join(TMPDIR, line.split()[0]),
os.path.join(package_path, line.split()[0]))
示例8: __init__
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def __init__(self, name=None, default_params={}):
"""name is going to be the generic name of the config folder
e.g., /home/user/.config/<name>/<name>.cfg
"""
if name is None:
raise Exception("Name parameter must be provided")
else:
# use input parameters
self.name = name
self._default_params = copy.deepcopy(default_params)
self.params = copy.deepcopy(default_params)
# useful tool to handle XDG config file, path and parameters
self.appdirs = appdirs.AppDirs(self.name)
# useful tool to handle the config ini file
self.config_parser = DynamicConfigParser()
# Now, create the missing directories if needed
self.init() # and read the user config file updating params if needed
示例9: compile_bundle_entry
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def compile_bundle_entry(self, spec, entry):
"""
Handler for each entry for the bundle method of the compile
process. This copies the source file or directory into the
build directory.
"""
modname, source, target, modpath = entry
bundled_modpath = {modname: modpath}
bundled_target = {modname: target}
export_module_name = []
if isfile(source):
export_module_name.append(modname)
copy_target = join(spec[BUILD_DIR], target)
if not exists(dirname(copy_target)):
makedirs(dirname(copy_target))
shutil.copy(source, copy_target)
elif isdir(source):
copy_target = join(spec[BUILD_DIR], modname)
shutil.copytree(source, copy_target)
return bundled_modpath, bundled_target, export_module_name
示例10: _ShareUpload
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def _ShareUpload(self, source_log: Text, share: Text):
"""Copy the log file to a network file share.
Args:
source_log: Path to the source log file to be copied.
share: The destination share to copy the file to.
Raises:
LogCopyError: Failure to mount share and copy log.
"""
creds = LogCopyCredentials()
username = creds.GetUsername()
password = creds.GetPassword()
mapper = drive_map.DriveMap()
result = mapper.MapDrive('l:', share, username, password)
if result:
destination = self._GetLogFileName()
try:
shutil.copy(source_log, destination)
except shutil.Error:
raise LogCopyError('Log copy failed.')
mapper.UnmapDrive('l:')
else:
raise LogCopyError('Drive mapping failed.')
示例11: gen_bpg
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def gen_bpg(in_images, out_dir, qs, first_n):
if '*' not in in_images:
in_images = os.path.join(in_images, '*.png')
images = sorted(glob.glob(in_images))[:first_n]
assert len(images) > 0, 'No matches for {}'.format(in_images)
for img in images:
if 'tmp' in img:
print('Skipping {}'.format(img))
continue
shutil.copy(img, os.path.join(out_dir, os.path.basename(img).replace('.png', '_base.png')))
print(os.path.basename(img))
for q in qs:
with remove_file_after(bpg_compress(img, q=q, tmp_dir=out_dir, chroma_fmt='422')) as p:
bpp = bpp_of_bpg_image(p)
out_png = decode_bpg_to_png(p)
out_name = os.path.basename(img).replace('.png', '_{:.4f}.png'.format(bpp))
out_p = os.path.join(out_dir, out_name)
print('-> {:.3f}: {}'.format(bpp, out_name))
os.rename(out_png, out_p)
示例12: main
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def main():
p = argparse.ArgumentParser('Copy deterministic subset of images to another directory.')
p.add_argument('root_dir')
p.add_argument('max_imgs', type=int)
p.add_argument('out_dir')
p.add_argument('--dry')
p.add_argument('--verbose', '-v', action='store_true')
flags = p.parse_args()
os.makedirs(flags.out_dir, exist_ok=True)
t = Testset(flags.root_dir, flags.max_imgs)
def cp(p1, p2):
if os.path.isfile(p2):
print('Exists, skipping: {}'.format(p2))
return
if flags.verbose:
print('cp {} -> {}'.format(p1, p2))
if not flags.dry:
shutil.copy(p1, p2)
for p in t.iter_orig_paths():
cp(p, os.path.join(flags.out_dir, os.path.basename(p)))
示例13: process
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def process(self, p_in):
fn, ext = os.path.splitext(os.path.basename(p_in))
if fn in self.images_cleaned:
return 1
if fn in self.images_discarded:
return 0
try:
im = Image.open(p_in)
except OSError as e:
print(f'\n*** Error while opening {p_in}: {e}')
return 0
im_out = random_resize_or_discard(im, self.min_res)
if im_out is not None:
p_out = join(self.out_dir_clean, fn + '.png') # Make sure to use .png!
im_out.save(p_out)
return 1
else:
p_out = join(self.out_dir_discard, os.path.basename(p_in))
shutil.copy(p_in, p_out)
return 0
示例14: _check_kernel
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def _check_kernel(self):
"""
If this file contains a kernel version string, assume it is a kernel.
Only Linux kernels are currently extracted.
"""
if not self.get_kernel_status():
for module in binwalk.scan(self.item, "-y", "kernel",
signature=True, quiet=True):
for entry in module.results:
if "kernel version" in entry.description:
self.update_database("kernel_version",
entry.description)
if "Linux" in entry.description:
if self.get_kernel_path():
shutil.copy(self.item, self.get_kernel_path())
else:
self.extractor.do_kernel = False
self.printf(">>>> %s" % entry.description)
return True
# VxWorks, etc
else:
self.printf(">>>> Ignoring: %s" % entry.description)
return False
return False
return False
示例15: get_data
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copy [as 別名]
def get_data():
filenames = [os.path.splitext(f)[0] for f in glob.glob("original/*.jpg")]
jpg_files = [s + ".jpg" for s in filenames]
txt_files = [s + ".txt" for s in filenames]
for file in txt_files:
boxes = []
with open(file, "r", encoding="utf-8", newline="") as lines:
for line in csv.reader(lines):
boxes.append([line[0], line[1], line[6], line[7]])
with open('mlt/label/' + file.split('/')[1], "w+") as labelFile:
wr = csv.writer(labelFile)
wr.writerows(boxes)
for jpg in jpg_files:
shutil.copy(jpg, 'mlt/image/')