我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用os.removedirs()。
def t05(w,h): pretty = '%s t5' % __file__ print(pretty) result_path = w.make_tempdir() os.chmod(result_path, stat.S_IRUSR) # user read permission only try: h.run_gtest('some_target', result_path) print( 'FAIL %s: expected error (not writable result directory): %s' % (pretty, temp_dir) ) return False except Exception as e: if e.message != 'result_path not a writable directory: %s' % result_path: print('FAIL %s: wrong error message: %s' % (pretty, str(e))) return False finally: os.removedirs(result_path) return True # successful execution of run_gtest(): check files on host, verfiy their # content and that traces from run removed from handset
def RemoveAllStalePycFiles(base_dir): """Scan directories for old .pyc files without a .py file and delete them.""" for dirname, _, filenames in os.walk(base_dir): if '.svn' in dirname or '.git' in dirname: continue for filename in filenames: root, ext = os.path.splitext(filename) if ext != '.pyc': continue pyc_path = os.path.join(dirname, filename) py_path = os.path.join(dirname, root + '.py') try: if not os.path.exists(py_path): os.remove(pyc_path) except OSError: # Wrap OS calls in try/except in case another process touched this file. pass try: os.removedirs(dirname) except OSError: # Wrap OS calls in try/except in case another process touched this dir. pass
def _init_dirs(self): test_dirs = ['a a', 'b', 'c\c', 'D_'] config = 'improbable' root = tempfile.mkdtemp() def cleanup(): try: os.removedirs(root) except (FileNotFoundError, OSError): pass os.chdir(root) for dir_ in test_dirs: os.mkdir(dir_, 0o0750) f = '{0}.toml'.format(config) flags = os.O_WRONLY | os.O_CREAT rel_path = '{0}/{1}'.format(dir_, f) abs_file_path = os.path.join(root, rel_path) with os.fdopen(os.open(abs_file_path, flags, 0o0640), 'w') as fp: fp.write("key = \"value is {0}\"\n".format(dir_)) return root, config, cleanup
def test_se_tardata_sudokus(file_path_base): try: image_file_name = file_path_base + '.jpg' image = load_image(image_file_name) except: image_file_name = file_path_base + '.png' image = load_image(image_file_name) with open(file_path_base + '.txt', 'rt') as f: correct_parsing = f.read().strip() predictions, sudoku, subimage = extract_sudoku(image, classifier(), force=True) parsed_sudoku = predictions_to_suduko_string(predictions, oneliner=False) if parsed_sudoku != correct_parsing: predictions, sudoku, subimage = extract_sudoku(image.rotate(-90), classifier(), force=True) parsed_sudoku = predictions_to_suduko_string(predictions, oneliner=False) assert parsed_sudoku == correct_parsing try: os.remove(image_file_name) os.remove(file_path_base + '.txt') print("Deleted temporary test dir.") os.removedirs(os.path.dirname(file_path_base)) except: pass
def delete_page(self, title, author=u'', comment=u''): """ Remove empty directories after deleting a page. Note that Mercurial doesn't track directories, so we don't have to commit after removing empty directories. """ super(WikiSubdirectoryStorage, self).delete_page(title, author, comment) file_path = self._file_path(title) self._check_path(file_path) dir_path = os.path.dirname(file_path) try: os.removedirs(dir_path) except OSError, e: pass # Ignore possibly OSError (39) Directory not empty errors.
def on_tableview_context_menu_delete(self): reply = QMessageBox.question(self, translate('message','Message'), translate('message',"Are you sure to DELETE?"), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.statusBar.showMessage(translate('statusbar',"Deleting...")) import shutil for Filename, Path, fullpath, IsFolder in self.get_tableview_selected(): logger.info("Delete: " + fullpath) # if not os.path.exists(Path): continue try: if IsFolder: os.removedirs(fullpath) else: os.remove(fullpath) except: logger.error("Fail to delete file: %s" % fullpath) self.statusBar.showMessage(translate('statusbar',"Done."), 3000)
def __init__(self,filepath): self.imgpath = filepath self.fonts =[] #??????????? self.str = '' #?????????? binaryimg = 'wower_binary.png' cutdir = './cutimgs/' #????binary???cutimgs??? if os.path.exists(binaryimg): os.remove(binaryimg) if os.path.exists(cutdir) and os.path.isdir(cutdir): for f in os.listdir(cutdir): os.remove(cutdir+f) # os.removedirs(cutdir) #????? else: os.mkdir(cutdir) #???????????
def __init__(self,filepath): self.imgpath = filepath self.fonts =[] #??????????? self.str = '' #?????????? binaryimg = 'binary.png' cutdir = './cutimgs/' #????binary???cutimgs??? if os.path.exists(binaryimg): os.remove(binaryimg) if os.path.exists(cutdir) and os.path.isdir(cutdir): for f in os.listdir(cutdir): os.remove(cutdir+f) os.removedirs(cutdir) #?????? os.mkdir(cutdir) #???????????
def __init__(self,filepath): self.imgpath = filepath self.fonts =[] #??????????? self.str = '' #?????????? binaryimg = 'hefeicc_binary.png' cutdir = './cutimgs/' #????binary???cutimgs??? if os.path.exists(binaryimg): os.remove(binaryimg) if os.path.exists(cutdir) and os.path.isdir(cutdir): for f in os.listdir(cutdir): os.remove(cutdir+f) # os.removedirs(cutdir) #????? else: os.mkdir(cutdir) #???????????
def test_create_directory(self): """ Test to create a new directory. """ # set up cache_path = "/tmp/kalliope/tests/testDirectory" if os.path.exists(cache_path): os.removedirs(cache_path) # Test FileManager.create_directory FileManager.create_directory(cache_path) self.assertTrue(os.path.exists(cache_path), "Fail creating a directory to the path ") # Remove the directory os.removedirs(cache_path)
def _process_upload(self, upl, session_id): path = os.path.join(self.db.dbdir, '_attachments', upl['path']) print 'processing', path # XXX: use a tempdir outdir = os.path.join(self.db.dbdir, upl['filename']) sess = SocketTranscriptionSession(outdir, self.factory, session_id, self.factory.gen_hclg_filename) BUF_LEN = 200 for chunk in numm3.sound_chunks(path, nchannels=1, R=8000, chunksize=BUF_LEN): sess.feed(chunk) sess.stop() sess.join() # Clean up: remove the tempdir and the original upload os.removedirs(outdir) os.remove(path)
def klasor_silme(): dizin = {} print "\nno\t\tdosya ad?\n--\t\t---------" for a, i in enumerate(os.listdir(os.curdir)): print "{}\t\t{}".format(a, i) dizin[a] = i try: d_no = input("Silmek istedi?iniz dosya numaras?: ") path = dizin[d_no] os.removedirs(path) except KeyError: print "Klasör silinemedi !" except NameError: print "Klasör silinemedi !" except SyntaxError: print "Klasör silinemedi !"
def _initialize(self): self.data_available = False self.batch = None self.thresholds = None self.peaks = None self.data_lines = None self.threshold_lines = None self.peak_points = None self.output_directory = self.path if self.output_directory is not None: if os.path.exists(self.output_directory): # TODO check that the directory contains only .svg files. # os.removedirs(self.output_directory) pass os.makedirs(self.output_directory) return
def renames(old, new): """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, tail = os.path.split(old) if head and tail: try: os.removedirs(head) except OSError: pass
def view_trigger_snippets(trigger_snippets, chans, save=None): # Create output directory if necessary. if os.path.exists(save): for f in os.listdir(save): p = os.path.join(save, f) os.remove(p) os.removedirs(save) os.makedirs(save) # Plot figures. fig = pylab.figure() for (c, chan) in enumerate(chans): ax = fig.add_subplot(1, 1, 1) for n in xrange(0, trigger_snippets.shape[2]): y = trigger_snippets[:, c, n] x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) b = 0.5 + 0.5 * numpy.random.rand() ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid') y = numpy.mean(trigger_snippets[:, c, :], axis=1) x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) ax.plot(x, y, color=(1.0, 0.0, 0.0), linestyle='solid') ax.grid(True) ax.set_xlim([numpy.amin(x), numpy.amax(x)]) ax.set_title("Channel %d" %chan) ax.set_xlabel("time") ax.set_ylabel("amplitude") if save is not None: # Save plot. filename = "channel-%d.png" %chan path = os.path.join(save, filename) pylab.savefig(path) fig.clf() if save is None: pylab.show() else: pylab.close(fig) return
def test_download_nest_dir(self): dir_name = 'data/ja' path = download(number=self.number, save_dir=dir_name) self.assertTrue(os.path.exists(path)) os.remove(path) os.removedirs(dir_name)
def __del__(self): if typepy.is_null_string(self.__temp_dir_path): return os.removedirs(self.__temp_dir_path) self.__temp_dir_path = None
def test_module_dir_params(self): """ tests module with dir params """ dir_name = tempfile.mkdtemp() invalid_params = {"data": dir_name, "schema": dir_name} self.options["module_args"] = json.dumps(invalid_params) results = run_module(self.options) msg = "Recursive directory not supported" output = results['failed'] and msg in results["msg"] os.removedirs(dir_name) assert_equal(output, True)
def test_module_dir_params(self): """ tests module with dir params """ dir_name = tempfile.mkdtemp() invalid_params = {"output_file": dir_name} self.options["module_args"] = json.dumps(invalid_params) results = run_module(self.options) msg = "Recursive directory not supported" output = results['failed'] and msg in results["msg"] os.removedirs(dir_name) assert_equal(output, True)
def test_module_dir_params(self): """ tests module with dir params """ dir_name = tempfile.mkdtemp() invalid_params = {"stack_name": "testname", "state": "present", "template": dir_name} self.options["module_args"] = json.dumps(invalid_params) results = run_module(self.options) msg = "Recursive directory not supported" output = results['failed'] and msg in results["msg"] assert_equal(output, True) os.removedirs(dir_name)
def clean_path(path): if not path: logging.info("Directory clean up - empty dir passed") return logging.info("Directory clean up - removing %s", path) try: # TODO: need to use osfs-rmdir on VSAN. For now jus yell if it failed os.removedirs(path) except Exception as e: logging.warning("Directory clean up failed - %s, err: %s", path, e)
def tearDown(self): """ Clear all PV,VG, LV and snapshots created by the test. """ # Remove created VG and unmount from base directory errs = [] for ramdisk in self.ramdisks: try: lv_utils.vg_ramdisk_cleanup(*ramdisk) except Exception as exc: errs.append("Fail to cleanup ramdisk %s: %s" % (ramdisk, exc)) if errs: self.error("\n".join(errs)) os.removedirs(self.mount_loc)
def clean(): absolute_path = os.path.abspath(__file__) mypath = os.path.dirname(absolute_path) for root, dirs, files in os.walk(mypath,topdown=False): for name in dirs: fname = join(root,name) if not os.listdir(fname): #to check wither the dir is empty os.removedirs(fname)
def cleanup(dir='test'): for path, dirs, files in os.walk(dir): for fn in files: os.remove(os.path.join(path, fn)) for dir in dirs: os.removedirs(os.path.join(path, dir)) # basic test