Python os.sep() Examples
The following are 30
code examples of os.sep().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
os
, or try the search function
.
Example #1
Source File: datasets.py From pruning_yolov3 with GNU General Public License v3.0 | 8 votes |
def convert_images2bmp(): # cv2.imread() jpg at 230 img/s, *.bmp at 400 img/s for path in ['../coco/images/val2014/', '../coco/images/train2014/']: folder = os.sep + Path(path).name output = path.replace(folder, folder + 'bmp') if os.path.exists(output): shutil.rmtree(output) # delete output folder os.makedirs(output) # make new output folder for f in tqdm(glob.glob('%s*.jpg' % path)): save_name = f.replace('.jpg', '.bmp').replace(folder, folder + 'bmp') cv2.imwrite(save_name, cv2.imread(f)) for label_path in ['../coco/trainvalno5k.txt', '../coco/5k.txt']: with open(label_path, 'r') as file: lines = file.read() lines = lines.replace('2014/', '2014bmp/').replace('.jpg', '.bmp').replace( '/Users/glennjocher/PycharmProjects/', '../') with open(label_path.replace('5k', '5k_bmp'), 'w') as file: file.write(lines)
Example #2
Source File: osdriver.py From multibootusb with GNU General Public License v2.0 | 7 votes |
def resource_path(relativePath): """ Function to detect the correct path of file when working with sourcecode/install or binary. :param relativePath: Path to file/data. :return: Modified path to file/data. """ # This is not strictly needed because Windows recognize '/' # as a path separator but we follow the discipline here. relativePath = relativePath.replace('/', os.sep) for dir_ in [ os.path.abspath('.'), os.path.abspath('..'), getattr(sys, '_MEIPASS', None), os.path.dirname(os.path.dirname( # go up two levels os.path.realpath(__file__))), '/usr/share/multibootusb'.replace('/', os.sep), ]: if dir_ is None: continue fullpath = os.path.join(dir_, relativePath) if os.path.exists(fullpath): return fullpath log("Could not find resource '%s'." % relativePath)
Example #3
Source File: cyberduck.py From Radium with Apache License 2.0 | 6 votes |
def get_path(self): if 'APPDATA' in os.environ: directory = os.environ['APPDATA'] + '\Cyberduck' if os.path.exists(directory): for dir in os.listdir(directory): if dir.startswith('Cyberduck'): for d in os.listdir(directory + os.sep + dir): path = directory + os.sep + dir + os.sep + d + os.sep + 'user.config' if os.path.exists(path): return path return 'User_profil_not_found' else: return 'CYBERDUCK_NOT_EXISTS' else: return 'APPDATA_NOT_FOUND' # parse the xml file
Example #4
Source File: mx_ide_eclipse.py From mx with GNU General Public License v2.0 | 6 votes |
def get_eclipse_project_rel_locationURI(path, eclipseProjectDir): """ Gets the URI for a resource relative to an Eclipse project directory (i.e., the directory containing the `.project` file for the project). The URI returned is based on the builtin PROJECT_LOC Eclipse variable. See http://stackoverflow.com/a/7585095 """ relpath = os.path.relpath(path, eclipseProjectDir) names = relpath.split(os.sep) parents = len([n for n in names if n == '..']) sep = '/' # Yes, even on Windows... if parents: projectLoc = 'PARENT-{}-PROJECT_LOC'.format(parents) else: projectLoc = 'PROJECT_LOC' return sep.join([projectLoc] + [n for n in names if n != '..'])
Example #5
Source File: freeze.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def get_resource_path(*args): if is_frozen(): # MEIPASS explanation: # https://pythonhosted.org/PyInstaller/#run-time-operation basedir = getattr(sys, '_MEIPASS', None) if not basedir: basedir = os.path.dirname(sys.executable) resource_dir = os.path.join(basedir, 'gooey') if not os.path.isdir(resource_dir): raise IOError( ("Cannot locate Gooey resources. It seems that the program was frozen, " "but resource files were not copied into directory of the executable " "file. Please copy `languages` and `images` folders from gooey module " "directory into `{}{}` directory. Using PyInstaller, a.datas in .spec " "file must be specified.".format(resource_dir, os.sep))) else: resource_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..')) return os.path.join(resource_dir, *args)
Example #6
Source File: lint.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def get_header_guard_dmlc(filename): """Get Header Guard Convention for DMLC Projects. For headers in include, directly use the path For headers in src, use project name plus path Examples: with project-name = dmlc include/dmlc/timer.h -> DMLC_TIMTER_H_ src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_ """ fileinfo = cpplint.FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() inc_list = ['include', 'api', 'wrapper'] if file_path_from_root.find('src/') != -1 and _HELPER.project_name is not None: idx = file_path_from_root.find('src/') file_path_from_root = _HELPER.project_name + file_path_from_root[idx + 3:] else: for spath in inc_list: prefix = spath + os.sep if file_path_from_root.startswith(prefix): file_path_from_root = re.sub('^' + prefix, '', file_path_from_root) break return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
Example #7
Source File: lint.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def get_header_guard_dmlc(filename): """Get Header Guard Convention for DMLC Projects. For headers in include, directly use the path For headers in src, use project name plus path Examples: with project-name = dmlc include/dmlc/timer.h -> DMLC_TIMTER_H_ src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_ """ fileinfo = cpplint.FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() inc_list = ['include', 'api', 'wrapper'] if file_path_from_root.find('src/') != -1 and _HELPER.project_name is not None: idx = file_path_from_root.find('src/') file_path_from_root = _HELPER.project_name + file_path_from_root[idx + 3:] else: for spath in inc_list: prefix = spath + os.sep if file_path_from_root.startswith(prefix): file_path_from_root = re.sub('^' + prefix, '', file_path_from_root) break return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
Example #8
Source File: loadables.py From zun with Apache License 2.0 | 6 votes |
def get_all_classes(self): """Get all classes Get the classes of the type we want from all modules found in the directory that defines this class. """ classes = [] for dirpath, dirnames, filenames in os.walk(self.path): relpath = os.path.relpath(dirpath, self.path) if relpath == '.': relpkg = '' else: relpkg = '.%s' % '.'.join(relpath.split(os.sep)) for fname in filenames: root, ext = os.path.splitext(fname) if ext != '.py' or root == '__init__': continue module_name = "%s%s.%s" % (self.package, relpkg, root) mod_classes = self._get_classes_from_module(module_name) classes.extend(mod_classes) return classes
Example #9
Source File: freshpaper.py From freshpaper with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_wallpaper_directory(): """ check if `default` wallpaper download directory exists or not, create if doesn't exist """ pictures_dir = "" wall_dir_name = "freshpaper" os.path.join(os.sep, os.path.expanduser("~"), "a", "freshpaper") if sys.platform.startswith("win32"): pictures_dir = "My Pictures" elif sys.platform.startswith("darwin"): pictures_dir = "Pictures" elif sys.platform.startswith("linux"): pictures_dir = "Pictures" wall_dir = os.path.join( os.sep, os.path.expanduser("~"), pictures_dir, wall_dir_name ) if not os.path.isdir(wall_dir): log.error("wallpaper directory does not exist.") os.makedirs(wall_dir) log.info("created wallpaper directory at: {}".format(wall_dir)) return wall_dir
Example #10
Source File: convert_coco_to_pkl.py From Yolo-v2-pytorch with MIT License | 6 votes |
def main(opt): ann_file = '{}/annotations/instances_{}.json'.format(opt.input, opt.type) dataset = json.load(open(ann_file, 'r')) image_dict = {} invalid_anno = 0 for image in dataset["images"]: if image["id"] not in image_dict.keys(): image_dict[image["id"]] = {"file_name": image["file_name"], "objects": []} for ann in dataset["annotations"]: if ann["image_id"] not in image_dict.keys(): invalid_anno += 1 continue image_dict[ann["image_id"]]["objects"].append( [int(ann["bbox"][0]), int(ann["bbox"][1]), int(ann["bbox"][0] + ann["bbox"][2]), int(ann["bbox"][1] + ann["bbox"][3]), ann["category_id"]]) pickle.dump(image_dict, open(opt.output + os.sep + 'COCO_{}.pkl'.format(opt.type), 'wb')) print ("There are {} invalid annotation(s)".format(invalid_anno))
Example #11
Source File: Mozilla.py From Radium with Apache License 2.0 | 6 votes |
def save_db(self, userpath): # create the folder to save it by profile relative_path = constant.folder_name + os.sep + 'firefox' if not os.path.exists(relative_path): os.makedirs(relative_path) relative_path += os.sep + os.path.basename(userpath) if not os.path.exists(relative_path): os.makedirs(relative_path) # Get the database name if os.path.exists(userpath + os.sep + 'logins.json'): dbname = 'logins.json' elif os.path.exists(userpath + os.sep + 'signons.sqlite'): dbname = 'signons.sqlite' # copy the files (database + key3.db) try: ori_db = userpath + os.sep + dbname dst_db = relative_path + os.sep + dbname shutil.copyfile(ori_db, dst_db) except Exception, e: pass
Example #12
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def from_path(cls, context, path): """ Create a device from a device ``path``. The ``path`` may or may not start with the ``sysfs`` mount point: >>> from pyudev import Context, Device >>> context = Context() >>> Devices.from_path(context, '/devices/platform') Device(u'/sys/devices/platform') >>> Devices.from_path(context, '/sys/devices/platform') Device(u'/sys/devices/platform') ``context`` is the :class:`Context` in which to search the device. ``path`` is a device path as unicode or byte string. Return a :class:`Device` object for the device. Raise :exc:`DeviceNotFoundAtPathError`, if no device was found for ``path``. .. versionadded:: 0.18 """ if not path.startswith(context.sys_path): path = os.path.join(context.sys_path, path.lstrip(os.sep)) return cls.from_sys_path(context, path)
Example #13
Source File: utils.py From dockerfiles with Apache License 2.0 | 6 votes |
def gen_dockerfile_path_from_tag(img_tag): """ sample input: 'tensorflow:1.0.1-gpu-py3' sample output: 'dl/tensorflow/1.0.1/Dockerfile-py3.gpu' """ match = docker_tag_re.match(img_tag) if not match: return None path_list = ['dl', match.group('project'), match.group('version')] filename = 'Dockerfile-' + match.group('env') arch = match.group('arch') if arch: filename += '.' + arch cloud = match.group('cloud') if cloud: filename += '_' + cloud path_list.append(filename) return os.path.sep.join(path_list)
Example #14
Source File: decompiler.py From dcc with Apache License 2.0 | 6 votes |
def _find_class(self, clname, basefolder): # check if defpackage if "/" not in clname: # this is a defpackage class probably... # Search first for defpackage, then search for requested string res = self._find_class("defpackage/{}".format(clname), basefolder) if res: return res # We try to map inner classes here if "$" in clname: # sometimes the inner class get's an extra file, sometimes not... # So we try all possibilities for x in range(clname.count("$")): tokens = clname.split("$", x + 1) base = "$".join(tokens[:-1]) res = self._find_class(base, basefolder) if res: return res # Check the whole supplied name fname = os.path.join(basefolder, clname.replace("/", os.sep) + ".java") if not os.path.isfile(fname): return None return fname
Example #15
Source File: cityscapes.py From overhaul-distillation with MIT License | 6 votes |
def __getitem__(self, index): img_path = self.files[self.split][index].rstrip() lbl_path = os.path.join(self.annotations_base, img_path.split(os.sep)[-2], os.path.basename(img_path)[:-15] + 'gtFine_labelIds.png') _img = Image.open(img_path).convert('RGB') _tmp = np.array(Image.open(lbl_path), dtype=np.uint8) _tmp = self.encode_segmap(_tmp) _target = Image.fromarray(_tmp) sample = {'image': _img, 'label': _target} if self.split == 'train': return self.transform_tr(sample) elif self.split == 'val': return self.transform_val(sample) elif self.split == 'test': return self.transform_ts(sample)
Example #16
Source File: saver.py From L3C-PyTorch with GNU General Public License v3.0 | 6 votes |
def __init__(self, out_dir=None, ckpt_name_fmt='ckpt_{:010d}.pt', tmp_postfix='.tmp'): assert len(tmp_postfix) assert '.' in tmp_postfix m = re.search(r'{:0(\d+?)d}', ckpt_name_fmt) assert m, 'Expected ckpt_name_fmt to have an int specifier such as or {:09d} or {:010d}.' max_itr = 10 ** int(m.group(1)) - 1 if max_itr < 10000000: # ten million, should be enough print(f'Maximum iteration supported: {max_itr}') assert os.sep not in ckpt_name_fmt self.ckpt_name_fmt = ckpt_name_fmt self.ckpt_prefix = ckpt_name_fmt.split('{')[0] assert len(self.ckpt_prefix), 'Expected ckpt_name_fmt to start with a prefix before the format part!' self.tmp_postfix = tmp_postfix self._out_dir = None if out_dir is not None: self.set_out_dir(out_dir)
Example #17
Source File: test_refactor.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def test_refactor_file_write_unchanged_file(self): test_file = os.path.join(FIXER_DIR, "parrot_example.py") debug_messages = [] def recording_log_debug(msg, *args): debug_messages.append(msg % args) self.check_file_refactoring(test_file, fixers=(), options={"write_unchanged_files": True}, mock_log_debug=recording_log_debug, actually_write=False) # Testing that it logged this message when write=False was passed is # sufficient to see that it did not bail early after "No changes". message_regex = r"Not writing changes to .*%s" % \ re.escape(os.sep + os.path.basename(test_file)) for message in debug_messages: if "Not writing changes" in message: self.assertRegex(message, message_regex) break else: self.fail("%r not matched in %r" % (message_regex, debug_messages))
Example #18
Source File: coverage.py From oscrypto with MIT License | 5 votes |
def _list_files(root): """ Lists all of the files in a directory, taking into account any .gitignore file that is present :param root: A unicode filesystem path :return: A list of unicode strings, containing paths of all files not ignored by .gitignore with root, using relative paths """ dir_patterns, file_patterns = _gitignore(root) paths = [] prefix = os.path.abspath(root) + os.sep for base, dirs, files in os.walk(root): for d in dirs: for dir_pattern in dir_patterns: if fnmatch(d, dir_pattern): dirs.remove(d) break for f in files: skip = False for file_pattern in file_patterns: if fnmatch(f, file_pattern): skip = True break if skip: continue full_path = os.path.join(base, f) if full_path[:len(prefix)] == prefix: full_path = full_path[len(prefix):] paths.append(full_path) return sorted(paths)
Example #19
Source File: chrome.py From Radium with Apache License 2.0 | 5 votes |
def run(self): database_path = '' if 'HOMEDRIVE' in os.environ and 'HOMEPATH' in os.environ: # For Win7 path_Win7 = os.environ.get('HOMEDRIVE') + os.environ.get( 'HOMEPATH') + '\Local Settings\Application Data\Google\Chrome\User Data\Default\Login Data' # For XP path_XP = os.environ.get('HOMEDRIVE') + os.environ.get( 'HOMEPATH') + '\AppData\Local\Google\Chrome\User Data\Default\Login Data' if os.path.exists(path_XP): database_path = path_XP elif os.path.exists(path_Win7): database_path = path_Win7 else: return else: return # Copy database before to query it (bypass lock errors) try: shutil.copy(database_path, os.getcwd() + os.sep + 'tmp_db') database_path = os.getcwd() + os.sep + 'tmp_db' except Exception, e: pass # Connect to the Database
Example #20
Source File: zipfile.py From jawfish with MIT License | 5 votes |
def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)): self.orig_filename = filename # Original file name in archive # Terminate the file name at the first null byte. Null bytes in file # names are used as tricks by viruses in archives. null_byte = filename.find(chr(0)) if null_byte >= 0: filename = filename[0:null_byte] # This is used to ensure paths in generated ZIP files always use # forward slashes as the directory separator, as required by the # ZIP format specification. if os.sep != "/" and os.sep in filename: filename = filename.replace(os.sep, "/") self.filename = filename # Normalized file name self.date_time = date_time # year, month, day, hour, min, sec if date_time[0] < 1980: raise ValueError('ZIP does not support timestamps before 1980') # Standard values: self.compress_type = ZIP_STORED # Type of compression for the file self.comment = b"" # Comment for each file self.extra = b"" # ZIP extra data if sys.platform == 'win32': self.create_system = 0 # System which created ZIP archive else: # Assume everything else is unix-y self.create_system = 3 # System which created ZIP archive self.create_version = DEFAULT_VERSION # Version which created ZIP archive self.extract_version = DEFAULT_VERSION # Version needed to extract archive self.reserved = 0 # Must be zero self.flag_bits = 0 # ZIP flag bits self.volume = 0 # Volume number of file header self.internal_attr = 0 # Internal attributes self.external_attr = 0 # External file attributes # Other attributes are set by class ZipFile: # header_offset Byte offset to the file header # CRC CRC-32 of the uncompressed file # compress_size Size of the compressed file # file_size Size of the uncompressed file
Example #21
Source File: pydoc.py From jawfish with MIT License | 5 votes |
def ispath(x): return isinstance(x, str) and x.find(os.sep) >= 0
Example #22
Source File: build.py From hand-detection.PyTorch with MIT License | 5 votes |
def locate_cuda(): """Locate the CUDA environment on the system Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64' and values giving the absolute path to each directory. Starts by looking for the CUDAHOME env variable. If not found, everything is based on finding 'nvcc' in the PATH. """ # first check if the CUDAHOME env variable is in use if 'CUDAHOME' in os.environ: home = os.environ['CUDAHOME'] nvcc = pjoin(home, 'bin', 'nvcc') else: # otherwise, search the PATH for NVCC default_path = pjoin(os.sep, 'usr', 'local', 'cuda', 'bin') nvcc = find_in_path('nvcc', os.environ['PATH'] + os.pathsep + default_path) if nvcc is None: raise EnvironmentError('The nvcc binary could not be ' 'located in your $PATH. Either add it to your path, or set $CUDAHOME') home = os.path.dirname(os.path.dirname(nvcc)) cudaconfig = {'home': home, 'nvcc': nvcc, 'include': pjoin(home, 'include'), 'lib64': pjoin(home, 'lib64')} for k, v in cudaconfig.items(): if not os.path.exists(v): raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v)) return cudaconfig
Example #23
Source File: utilities.py From pyGSTi with Apache License 2.0 | 5 votes |
def get_file_names(): fileNames = {} for subdir, _, files in os.walk(os.getcwd()): for filename in files: if filename.endswith('.py') and filename.startswith('test'): fileNames[filename] = subdir + os.sep + filename return fileNames # Wrapper for git diff
Example #24
Source File: test_init.py From oscrypto with MIT License | 5 votes |
def test_load_order(self): deps = {} mod_root = os.path.abspath(os.path.dirname(module.__file__)) files = [] for root, dnames, fnames in os.walk(mod_root): for f in fnames: if f.endswith('.py'): full_path = os.path.join(root, f) rel_path = full_path.replace(mod_root + os.sep, '') files.append((full_path, rel_path)) for full_path, rel_path in sorted(files): with open(full_path, 'rb') as f: full_code = f.read() if sys.version_info >= (3,): full_code = full_code.decode('utf-8') modname = rel_path.replace('.py', '').replace(os.sep, '.') if modname == '__init__': modname = module.__name__ else: modname = '%s.%s' % (module.__name__, modname) imports = set([]) module_node = ast.parse(full_code, filename=full_path) walk_ast(module_node, modname, imports) deps[modname] = imports load_order = module.load_order() prev = set([]) for mod in load_order: self.assertEqual(True, mod in deps) self.assertEqual((mod, set([])), (mod, deps[mod] - prev)) prev.add(mod)
Example #25
Source File: build.py From operator-courier with Apache License 2.0 | 5 votes |
def _get_relative_path(self, path): """ :param path: the path of the file :return: the file name along with its parent folder If the file is in the root directory from where it was called, just return the input path. """ path = os.path.normpath(path) parts = path.split(os.sep) if len(parts) > 1: return os.path.join(parts[-2], parts[-1]) else: return path
Example #26
Source File: fnmatch.py From pywren-ibm-cloud with Apache License 2.0 | 5 votes |
def filter(names, pat, norm_paths=True, case_sensitive=True, sep=None): """Return the subset of the list NAMES that match PAT.""" result = [] pat = _norm_paths(pat, norm_paths, sep) match = _compile_pattern(pat, case_sensitive) for name in names: m = match(_norm_paths(name, norm_paths, sep)) if m: result.append((name, tuple(_norm_paths(p, norm_paths, sep) for p in m.groups()))) return result
Example #27
Source File: fnmatch.py From pywren-ibm-cloud with Apache License 2.0 | 5 votes |
def fnmatch(name, pat, norm_paths=True, case_sensitive=True, sep=None): """Test whether FILENAME matches PATTERN. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq An initial period in FILENAME is not special. Both FILENAME and PATTERN are first case-normalized if the operating system requires it. If you don't want this, use fnmatchcase(FILENAME, PATTERN). :param slashes: :param norm_paths: A tri-state boolean: when true, invokes `os.path,.normcase()` on both paths, when `None`, just equalize slashes/backslashes to `os.sep`, when false, does not touch paths at all. Note that a side-effect of `normcase()` on *Windows* is that it converts to lower-case all matches of `?glob()` functions. :param case_sensitive: defines the case-sensitiviness of regex doing the matches :param sep: in case only slahes replaced, what sep-char to substitute with; if false, `os.sep` is used. Notice that by default, `normcase()` causes insensitive matching on *Windows*, regardless of `case_insensitive` param. Set ``norm_paths=None, case_sensitive=False`` to preserve verbatim mathces. """ name, pat = [_norm_paths(p, norm_paths, sep) for p in (name, pat)] return fnmatchcase(name, pat, case_sensitive=case_sensitive)
Example #28
Source File: fnmatch.py From pywren-ibm-cloud with Apache License 2.0 | 5 votes |
def _norm_paths(path, norm_paths, sep): if norm_paths is None: path = re.sub(r'\/', sep or os.sep, path) # cached internally elif norm_paths: path = os.path.normcase(path) return path
Example #29
Source File: cache.py From glazier with Apache License 2.0 | 5 votes |
def _DestinationPath(self, cache_path: Text, url: Text) -> Text: """Determines the local path for a file being downloaded. Args: cache_path: Path to the local build cache url: A web address to a file as a string Returns: The local disk path as a string. """ file_name = url.split('/').pop() destination = os.path.join(cache_path + os.sep, file_name) return destination
Example #30
Source File: public.py From tdw with GNU General Public License v3.0 | 5 votes |
def _makezip(self): open( self.sizepath, "w" ).write( str(os.path.getsize(self.libpath)) ) os.chdir(self.libdir) os.system('del %s' % (self.zipname)) os.system('"C:\\Program Files\\7-Zip\\7z.exe" a %s.zip %s' % (self.libname, self.libname)) os.chdir(self.root) #os.system('"C:\\Program Files\\7-Zip\\7z.exe" a %s.zip %s' % # (self.platform['system']+os.sep+self.libname, self.platform['system']+os.sep+self.libname))