query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
replace in file
python
def replace_in_file(filename: str, text_from: str, text_to: str) -> None: """ Replaces text in a file. Args: filename: filename to process (modifying it in place) text_from: original text to replace text_to: replacement text """ log.info("Amending {}: {} -> {}", filename, repr(text_from), repr(text_to)) with open(filename) as infile: contents = infile.read() contents = contents.replace(text_from, text_to) with open(filename, 'w') as outfile: outfile.write(contents)
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L390-L405
replace in file
python
def ReplaceInFile(filename, old, new, encoding=None): ''' Replaces all occurrences of "old" by "new" in the given file. :param unicode filename: The name of the file. :param unicode old: The string to search for. :param unicode new: Replacement string. :return unicode: The new contents of the file. ''' contents = GetFileContents(filename, encoding=encoding) contents = contents.replace(old, new) CreateFile(filename, contents, encoding=encoding) return contents
https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1117-L1136
replace in file
python
def replace_in_file(self, file_path, old_exp, new_exp): """ In the given file, replace all 'old_exp' by 'new_exp'. """ self.term.print_info(u"Making replacement into {}" .format(self.term.text_in_color(file_path, TERM_GREEN))) # write the new version into a temporary file tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False) for filelineno, line in enumerate(io.open(file_path, encoding="utf-8")): if old_exp in line: line = line.replace(old_exp, new_exp) try: tmp_file.write(line.encode('utf-8')) except TypeError: tmp_file.write(line) name = tmp_file.name # keep the name tmp_file.close() shutil.copy(name, file_path) # replace the original one os.remove(name)
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/templates/ProjyTemplate.py#L148-L166
replace in file
python
def copy_and_replace(file_in, file_out, mapping, **kwargs): ''' Copy a file and replace some placeholders with new values. ''' separator = '@@' if 'separator' in kwargs: separator = kwargs['separator'] file_in = open(file_in, 'r') file_out = open(file_out, 'w') s = file_in.read() for find, replace in mapping: find = separator + find + separator print(u'Replacing {0} with {1}'.format(find, replace)) s = s.replace(find, replace) file_out.write(s)
https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/deploy/__init__.py#L4-L18
replace in file
python
def replace_in_file(workspace, src_file_path, from_str, to_str): """Replace from_str with to_str in the name and content of the given file. If any edits were necessary, returns the new filename (which may be the same as the old filename). """ from_bytes = from_str.encode('ascii') to_bytes = to_str.encode('ascii') data = read_file(os.path.join(workspace, src_file_path), binary_mode=True) if from_bytes not in data and from_str not in src_file_path: return None dst_file_path = src_file_path.replace(from_str, to_str) safe_file_dump(os.path.join(workspace, dst_file_path), data.replace(from_bytes, to_bytes), mode='wb') if src_file_path != dst_file_path: os.unlink(os.path.join(workspace, src_file_path)) return dst_file_path
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/releases/reversion.py#L21-L38
replace in file
python
def _copy_replace(src, dst, replacements): """Copies the src file into dst applying the replacements dict""" with src.open() as infile, dst.open('w') as outfile: outfile.write(re.sub( '|'.join(re.escape(k) for k in replacements), lambda m: str(replacements[m.group(0)]), infile.read() ))
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon_generator/generators/docs.py#L199-L206
replace in file
python
def replace_in_file(args, in_file, regexp, repl): """ Perfoms re.sub(regexp, repl, line) for each line in in_file """ in_lines = [] try: with open(in_file, "r") as in_fd: in_lines = in_fd.readlines() except (OSError, UnicodeDecodeError) as error: print("Cant open file:", in_file, error) return out_lines = in_lines[:] out_lines = [re.sub(regexp, repl, l) for l in in_lines] # Exit early if there's no diff: if in_lines == out_lines: return if not args.quiet: display_diff(in_file, regexp, repl, in_lines, out_lines) if not args.go: return if args.backup: backup(in_file, in_lines) with open(in_file, "w") as fd: fd.writelines(out_lines)
https://github.com/dmerejkowsky/replacer/blob/8dc16f297d0ff3a6ee2fa3c0d77789a6859b0f6a/replacer.py#L203-L233
replace in file
python
def replace(state, host, name, match, replace, flags=None): ''' A simple shortcut for replacing text in files with sed. + name: target remote file to edit + match: text/regex to match for + replace: text to replace with + flags: list of flaggs to pass to sed ''' yield sed_replace(name, match, replace, flags=flags)
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/files.py#L169-L179
replace in file
python
def replace_text(filepath, to_replace, replacement): """ Replaces a string in a given file with another string :param file: the file in which the string has to be replaced :param to_replace: the string to be replaced in the file :param replacement: the string which replaces 'to_replace' in the file """ with open(filepath) as file: s = file.read() s = s.replace(to_replace, replacement) with open(filepath, 'w') as file: file.write(s)
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/report.py#L812-L824
replace in file
python
def replace_file(from_file, to_file): """ Replaces to_file with from_file """ try: os.remove(to_file) except OSError: pass copy(from_file, to_file)
https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/modeling/framework.py#L29-L37
replace in file
python
def replace_file(src, dst): """ Overwrite a file (in an atomic fashion when possible). :param src: The pathname of the source file (a string). :param dst: The pathname of the destination file (a string). """ # Try os.replace() which was introduced in Python 3.3 # (this should work on POSIX as well as Windows systems). try: os.replace(src, dst) return except AttributeError: pass # Try os.rename() which is atomic on UNIX but refuses to overwrite existing # files on Windows. try: os.rename(src, dst) return except OSError as e: if e.errno != errno.EEXIST: raise # Finally we fall back to the dumb approach required only on Windows. # See https://bugs.python.org/issue8828 for a long winded discussion. os.remove(dst) os.rename(src, dst)
https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/utils.py#L203-L228
replace in file
python
def replace(oldstr, newstr, infile, dryrun=False): """ Sed-like Replace function.. Usage: pysed.replace(<Old string>, <Replacement String>, <Text File>) Example: pysed.replace('xyz', 'XYZ', '/path/to/file.txt') This will dump the output to STDOUT instead of changing the input file. Example 'DRYRUN': pysed.replace('xyz', 'XYZ', '/path/to/file.txt', dryrun=True) """ linelist = [] with open(infile) as reader: for item in reader: newitem = re.sub(oldstr, newstr, item) linelist.append(newitem) if dryrun is False: with open(infile, "w") as writer: writer.truncate() for line in linelist: writer.writelines(line) elif dryrun is True: for line in linelist: print(line, end='') else: exit("""Unknown option specified to 'dryrun' argument, Usage: dryrun=<True|False>.""")
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/utils/pysed.py#L12-L39
replace in file
python
def replace_f(self, path, arg_name=None): """Replace files""" root, file = os.path.split(path) pattern = re.compile(r'(\<\<\<)([A-Za-z_]+)(\>\>\>)') file_path = path fh, abs_path = mkstemp() with open(abs_path, 'w') as new_file: with open(file_path) as old_file: for line in old_file: for (o, var_name, c) in re.findall(pattern, line): line = self.handle_args(line, var_name, arg_name) new_file.write(line) os.close(fh) # Remove original file os.remove(file_path) # Move new file shutil.move(abs_path, file_path) pattern = re.compile(r'(\[\[)([A-Za-z_]+)(\]\])') for (o, var_name, c) in re.findall(pattern, file): file = self.handle_args(file, var_name, isfilename=True) os.rename(path, os.path.join(root, file))
https://github.com/char16t/wa/blob/ee28bf47665ea57f3a03a08dfc0a5daaa33d8121/wa/api.py#L152-L174
replace in file
python
def replace_text_dir(self, directory, to_replace, replacement, file_type=None): """ Replaces a string with its replacement in all the files in the directory :param directory: the directory in which the files have to be modified :param to_replace: the string to be replaced in the files :param replacement: the string which replaces 'to_replace' in the files :param file_type: file pattern to match the files in which the string has to be replaced """ if not file_type: file_type = "*.tex" for file in glob.iglob(os.path.join(directory, file_type)): self.replace_text(file, to_replace, replacement)
https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/report.py#L826-L838
replace in file
python
def replace_all(filepath, searchExp, replaceExp): """ Replace all the ocurrences (in a file) of a string with another value. """ for line in fileinput.input(filepath, inplace=1): if searchExp in line: line = line.replace(searchExp, replaceExp) sys.stdout.write(line)
https://github.com/danielfrg/datasciencebox/blob/6b7aa642c6616a46547035fcb815acc1de605a6f/datasciencebox/core/utils.py#L39-L46
replace in file
python
def replace(self, old, new): """ Replace all lines of file that match 'old' with 'new' Will replace duplicates if found. :param old: String, List of Strings, a multi-line String, or False; what to replace. :param new: String; what to use as replacement. :return: Boolean; whether contents changed during method call. """ self.log('replace({0}, {1})'.format(old, new)) if old is False: return False if isinstance(old, str): old = old.split('\n') if not isinstance(old, list): raise TypeError("Parameter 'old' not a 'string' or 'list', is {0}".format(type(old))) if not isinstance(new, str): raise TypeError("Parameter 'new' not a 'string', is {0}".format(type(new))) local_changes = False for this in old: if this in self.contents: while this in self.contents: index = self.contents.index(this) self.changed = local_changes = True self.contents.remove(this) self.contents.insert(index, new) self.log('Replaced "{0}" with "{1}" at line {2}'.format(this, new, index)) else: self.log('"{0}" not in {1}'.format(this, self.filename)) return local_changes
https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/fileasobj/__init__.py#L245-L276
replace in file
python
def replace_multiple_in_file(filename: str, replacements: List[Tuple[str, str]]) -> None: """ Replaces multiple from/to string pairs within a single file. Args: filename: filename to process (modifying it in place) replacements: list of ``(from_text, to_text)`` tuples """ with open(filename) as infile: contents = infile.read() for text_from, text_to in replacements: log.info("Amending {}: {} -> {}", filename, repr(text_from), repr(text_to)) contents = contents.replace(text_from, text_to) with open(filename, 'w') as outfile: outfile.write(contents)
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L408-L424
replace in file
python
def replace_ext(filename, new_ext): """Replace the file extention.""" filename_base = os.path.splitext(filename)[0] new_filename = '{}.{}'.format(filename_base, new_ext) return new_filename
https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/files.py#L12-L16
replace in file
python
def replace_in_files(search, replace, depth=0, paths=None, confirm=True): """ Does a line-by-line search and replace, but only up to the "depth" line. """ # have the user select some files if paths==None: paths = _s.dialogs.MultipleFiles('DIS AND DAT|*.*') if paths == []: return for path in paths: lines = read_lines(path) if depth: N=min(len(lines),depth) else: N=len(lines) for n in range(0,N): if lines[n].find(search) >= 0: lines[n] = lines[n].replace(search,replace) print(path.split(_os.path.pathsep)[-1]+ ': "'+lines[n]+'"') # only write if we're not confirming if not confirm: _os.rename(path, path+".backup") write_to_file(path, join(lines, '')) if confirm: if input("yes? ")=="yes": replace_in_files(search,replace,depth,paths,False) return
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_functions.py#L1232-L1262
replace in file
python
def replace_in_files(dirname, replace): """Replace current version with new version in requirements files.""" filepath = os.path.abspath(dirname / "requirements.in") if os.path.isfile(filepath) and header_footer_exists(filepath): replaced = re.sub(Utils.exp, replace, get_file_string(filepath)) with open(filepath, "w") as f: f.write(replaced) print(color( "Written to file: {}".format(filepath), fg='magenta', style='bold'))
https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/scripts/upgrade_header_footer.py#L70-L79
replace in file
python
def _replace_file(path, content): """Writes a file if it doesn't already exist with the same content. This is useful because cargo uses timestamps to decide whether to compile things.""" if os.path.exists(path): with open(path, 'r') as f: if content == f.read(): print("Not overwriting {} because it is unchanged".format(path), file=sys.stderr) return with open(path, 'w') as f: f.write(content)
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/native.py#L183-L194
replace in file
python
def replace_directory(out_files, dest_dir): """ change the output directory to dest_dir can take a string (single file) or a list of files """ if is_sequence(out_files): filenames = map(os.path.basename, out_files) return [os.path.join(dest_dir, x) for x in filenames] elif is_string(out_files): return os.path.join(dest_dir, os.path.basename(out_files)) else: raise ValueError("in_files must either be a sequence of filenames " "or a string")
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L624-L637
replace in file
python
def _replace(variables, match): """ Return the appropriate replacement for `match` using the passed variables """ expression = match.group(1) # Look-up chars and functions for the specified operator (prefix_char, separator_char, split_fn, escape_fn, format_fn) = operator_map.get(expression[0], defaults) replacements = [] for key, modify_fn, explode in split_fn(expression): if key in variables: variable = modify_fn(variables[key]) replacement = format_fn( explode, separator_char, escape_fn, key, variable) replacements.append(replacement) if not replacements: return '' return prefix_char + separator_char.join(replacements)
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/template.py#L195-L214
replace in file
python
def sed_inplace(filename, pattern, repl): ''' Perform the pure-Python equivalent of in-place `sed` substitution: e.g., `sed -i -e 's/'${pattern}'/'${repl}' "${filename}"`. ''' # For efficiency, precompile the passed regular expression. pattern_compiled = re.compile(pattern) # For portability, NamedTemporaryFile() defaults to mode "w+b" # (i.e., binary writing with updating). # This is usually a good thing. In this case, # however, binary writing # imposes non-trivial encoding constraints trivially # resolved by switching to text writing. Let's do that. with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file: with open(filename) as src_file: for line in src_file: tmp_file.write(pattern_compiled.sub(repl, line)) # Overwrite the original file with the munged temporary file in a # manner preserving file attributes (e.g., permissions). shutil.copystat(filename, tmp_file.name) shutil.move(tmp_file.name, filename)
https://github.com/mcocdawc/chemcoord/blob/95561ce387c142227c38fb14a1d182179aef8f5f/version.py#L17-L38
replace in file
python
def replace_file_content(filepath, old, new, max=1): """ Modify the content of `filepath`, replacing `old` for `new`. Parameters ---------- filepath: str Path to the file to be modified. It will be overwritten. old: str This is old substring to be replaced. new: str This is new substring, which would replace old substring. max: int If larger than 0, Only the first `max` occurrences are replaced. """ with open(filepath, 'r') as f: content = f.read() content = content.replace(old, new, max) with open(filepath, 'w') as f: f.write(content)
https://github.com/PythonSanSebastian/docstamp/blob/b43808f2e15351b0b2f0b7eade9c7ef319c9e646/docstamp/file_utils.py#L198-L220
replace in file
python
def replace(name, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', show_changes=True, ignore_if_missing=False, backslash_literal=False): r''' Maintain an edit in a file. .. versionadded:: 0.17.0 name Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`re.search`. .. note:: If you need to match a literal string that contains regex special characters, you may want to use salt's custom Jinja filter, ``regex_escape``. .. code-block:: jinja {{ 'http://example.com?foo=bar%20baz' | regex_escape }} repl The replacement text count Maximum number of pattern occurrences to be replaced. Defaults to 0. If count is a positive integer n, no more than n occurrences will be replaced, otherwise all occurrences will be replaced. flags A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to ``8`` (which equates to ``['MULTILINE']``). .. note:: ``file.replace`` reads the entire file as a string to support multiline regex patterns. Therefore, when using anchors such as ``^`` or ``$`` in the pattern, those anchors may be relative to the line OR relative to the file. The default for ``file.replace`` is to treat anchors as relative to the line, which is implemented by setting the default value of ``flags`` to ``['MULTILINE']``. When overriding the default value for ``flags``, if ``'MULTILINE'`` is not present then anchors will be relative to the file. If the desired behavior is for anchors to be relative to the line, then simply add ``'MULTILINE'`` to the list of flags. bufsize How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False If set to ``True``, and pattern is not found, then the content will be appended to the file. .. versionadded:: 2014.7.0 prepend_if_not_found : False If set to ``True`` and pattern is not found, then the content will be prepended to the file. .. versionadded:: 2014.7.0 not_found_content Content to use for append/prepend if not found. If ``None`` (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. .. versionadded:: 2014.7.0 backup The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. show_changes : True Output a unified diff of the old file and the new file. If ``False`` return a boolean if any changes were made. Returns a boolean or a string. .. note: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2016.3.4 Controls what to do if the file is missing. If set to ``False``, the state will display an error raised by the execution module. If set to ``True``, the state will simply report no changes. backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. For complex regex patterns, it can be useful to avoid the need for complex quoting and escape sequences by making use of YAML's multiline string syntax. .. code-block:: yaml complex_search_and_replace: file.replace: # <...snip...> - pattern: | CentOS \(2.6.32[^\\n]+\\n\s+root[^\\n]+\\n\)+ .. note:: When using YAML multiline string syntax in ``pattern:``, make sure to also use that syntax in the ``repl:`` part, or you might loose line feeds. When regex capture groups are used in ``pattern:``, their captured value is available for reuse in the ``repl:`` part as a backreference (ex. ``\1``). .. code-block:: yaml add_login_group_to_winbind_ssh_access_list: file.replace: - name: '/etc/security/pam_winbind.conf' - pattern: '^(require_membership_of = )(.*)$' - repl: '\1\2,append-new-group-to-line' .. note:: The ``file.replace`` state uses Python's ``re`` module. For more advanced options, see https://docs.python.org/2/library/re.html ''' name = os.path.expanduser(name) ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} if not name: return _error(ret, 'Must provide name to file.replace') check_res, check_msg = _check_file(name) if not check_res: if ignore_if_missing and 'file not found' in check_msg: ret['comment'] = 'No changes needed to be made' return ret else: return _error(ret, check_msg) changes = __salt__['file.replace'](name, pattern, repl, count=count, flags=flags, bufsize=bufsize, append_if_not_found=append_if_not_found, prepend_if_not_found=prepend_if_not_found, not_found_content=not_found_content, backup=backup, dry_run=__opts__['test'], show_changes=show_changes, ignore_if_missing=ignore_if_missing, backslash_literal=backslash_literal) if changes: ret['changes']['diff'] = changes if __opts__['test']: ret['result'] = None ret['comment'] = 'Changes would have been made' else: ret['result'] = True ret['comment'] = 'Changes were made' else: ret['result'] = True ret['comment'] = 'No changes needed to be made' return ret
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L4478-L4676
replace in file
python
def replace(self, match, content): """Replace all occurences of the regex in all matches from a file with a specific value. """ new_string = self.replace_expression.sub(self.replace_with, match) logger.info('Replacing: [ %s ] --> [ %s ]', match, new_string) new_content = content.replace(match, new_string) return new_content
https://github.com/cloudify-cosmo/repex/blob/589e442857fa4a99fa88670d7df1a72f983bbd28/repex.py#L623-L630
replace in file
python
def replace( fname1, fname2, dfilter1, dfilter2, has_header1=True, has_header2=True, frow1=0, frow2=0, ofname=None, ocols=None, ): r""" Replace data in one file with data from another file. :param fname1: Name of the input comma-separated values file, the file that contains the columns to be replaced :type fname1: FileNameExists_ :param fname2: Name of the replacement comma-separated values file, the file that contains the replacement data :type fname2: FileNameExists_ :param dfilter1: Row and/or column filter for the input file :type dfilter1: :ref:`CsvDataFilter` :param dfilter2: Row and/or column filter for the replacement file :type dfilter2: :ref:`CsvDataFilter` :param has_header1: Flag that indicates whether the input comma-separated values file has column headers in its first line (True) or not (False) :type has_header1: boolean :param has_header2: Flag that indicates whether the replacement comma-separated values file has column headers in its first line (True) or not (False) :type has_header2: boolean :param frow1: Input comma-separated values file first data row (starting from 1). If 0 the row where data starts is auto-detected as the first row that has a number (integer of float) in at least one of its columns :type frow1: NonNegativeInteger_ :param frow2: Replacement comma-separated values file first data row (starting from 1). If 0 the row where data starts is auto-detected as the first row that has a number (integer of float) in at least one of its columns :type frow2: NonNegativeInteger_ :param ofname: Name of the output comma-separated values file, the file that will contain the input file data but with some columns replaced with data from the replacement file. If None the input file is replaced "in place" :type ofname: FileName_ :param ocols: Names of the replaced columns in the output comma-separated values file. If None the column names in the input file are used if **has_header1** is True, otherwise no header is used :type ocols: list or None .. [[[cog cog.out(exobj.get_sphinx_autodoc(raised=True)) ]]] .. Auto-generated exceptions documentation for pcsv.replace.replace :raises: * OSError (File *[fname]* could not be found) * RuntimeError (Argument \`dfilter1\` is not valid) * RuntimeError (Argument \`dfilter2\` is not valid) * RuntimeError (Argument \`fname1\` is not valid) * RuntimeError (Argument \`fname2\` is not valid) * RuntimeError (Argument \`frow1\` is not valid) * RuntimeError (Argument \`frow2\` is not valid) * RuntimeError (Argument \`ocols\` is not valid) * RuntimeError (Argument \`ofname\` is not valid) * RuntimeError (Column headers are not unique in file *[fname]*) * RuntimeError (File *[fname]* has no valid data) * RuntimeError (File *[fname]* is empty) * RuntimeError (Invalid column specification) * RuntimeError (Number of input and output columns are different) * RuntimeError (Number of input and replacement columns are different) * ValueError (Column *[column_identifier]* not found) * ValueError (Number of rows mismatch between input and replacement data) .. [[[end]]] """ # pylint: disable=R0913,R0914 irmm_ex = pexdoc.exh.addex( RuntimeError, "Number of input and replacement columns are different" ) iomm_ex = pexdoc.exh.addex( RuntimeError, "Number of input and output columns are different" ) # Read and validate input data iobj = CsvFile(fname=fname1, dfilter=dfilter1, has_header=has_header1, frow=frow1) # Read and validate replacement data robj = CsvFile(fname=fname2, dfilter=dfilter2, has_header=has_header2, frow=frow2) # Assign output data structure ofname = fname1 if ofname is None else ofname icfilter = iobj.header() if iobj.cfilter is None else iobj.cfilter rcfilter = robj.header() if robj.cfilter is None else robj.cfilter ocols = icfilter if ocols is None else ocols # Miscellaneous data validation irmm_ex(len(icfilter) != len(rcfilter)) iomm_ex(len(icfilter) != len(ocols)) # Replace data iobj.replace(rdata=robj.data(filtered=True), filtered=True) iheader_upper = [ item.upper() if isinstance(item, str) else item for item in iobj.header() ] icfilter_index = [ iheader_upper.index(item.upper() if isinstance(item, str) else item) for item in icfilter ] # Create new header orow = [] if has_header1: for col_num, idata in enumerate(iobj.header()): orow.append( ocols[icfilter_index.index(col_num)] if col_num in icfilter_index else idata ) # Write (new) file iobj.write(fname=ofname, header=orow if orow else False, append=False)
https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/replace.py#L43-L186
replace in file
python
def replace_suffix(to_transform, suffix): """ replaces the suffix on a filename or list of filenames example: replace_suffix("/path/to/test.sam", ".bam") -> "/path/to/test.bam" """ if is_sequence(to_transform): transformed = [] for f in to_transform: (base, _) = os.path.splitext(f) transformed.append(base + suffix) return transformed elif is_string(to_transform): (base, _) = os.path.splitext(to_transform) return base + suffix else: raise ValueError("replace_suffix takes a single filename as a string or " "a list of filenames to transform.")
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L411-L429
replace in file
python
def replaceext(filepath, new_ext): """Replace any existing file extension with a new one Example:: >>> replaceext('/foo/bar.txt', 'py') '/foo/bar.py' >>> replaceext('/foo/bar.txt', '.doc') '/foo/bar.doc' Args: filepath (str, path): file path new_ext (str): new file extension; if a leading dot is not included, it will be added. Returns: Tuple[str] """ if new_ext and new_ext[0] != '.': new_ext = '.' + new_ext root, ext = os.path.splitext(safepath(filepath)) return root + new_ext
https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L26-L48
replace in file
python
def _str_replace(txt): """Makes a small text amenable to being used in a filename.""" txt = txt.replace(",", "") txt = txt.replace(" ", "_") txt = txt.replace(":", "") txt = txt.replace(".", "") txt = txt.replace("/", "") txt = txt.replace("", "") return txt
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj.py#L267-L275
replace in file
python
def replace_first_key_in_makefile(buf, key, replacement, outfile=None): ''' Replaces first line in 'buf' matching 'key' with 'replacement'. Optionally, writes out this new buffer into 'outfile'. Returns: Buffer after replacement has been done ''' regexp = re.compile(r''' \n\s* # there might be some leading spaces ( # start group to return (?:{0}\s*) # placeholder for tags to detect '\S+' == all \s*:*=\s* # optional spaces, optional colon, = , optional spaces .* # the value ) # end group to return '''.format(key), re.VERBOSE) matches = regexp.findall(buf) if matches is None: msg = "Could not find key = {0} in the provided buffer. "\ "Pattern used = {1}".format(key, regexp.pattern) raise ValueError(msg) # Only replace the first occurence newbuf = regexp.sub(replacement, buf, count=1) if outfile is not None: write_text_file(outfile, newbuf) return newbuf
https://github.com/manodeep/Corrfunc/blob/753aa50b93eebfefc76a0b0cd61522536bd45d2a/setup.py#L147-L174
replace in file
python
def sed(file_path, pattern, replace_str, g=0): """Python impl of the bash sed command This method emulates the functionality of a bash sed command. :param file_path: (str) Full path to the file to be edited :param pattern: (str) Search pattern to replace as a regex :param replace_str: (str) String to replace the pattern :param g: (int) Whether to globally replace (0) or replace 1 instance (equivalent to the 'g' option in bash sed :return: None :raises CommandError """ log = logging.getLogger(mod_logger + '.sed') # Type checks on the args if not isinstance(file_path, basestring): msg = 'file_path argument must be a string' log.error(msg) raise CommandError(msg) if not isinstance(pattern, basestring): msg = 'pattern argument must be a string' log.error(msg) raise CommandError(msg) if not isinstance(replace_str, basestring): msg = 'replace_str argument must be a string' log.error(msg) raise CommandError(msg) # Ensure the file_path file exists if not os.path.isfile(file_path): msg = 'File not found: {f}'.format(f=file_path) log.error(msg) raise CommandError(msg) # Search for a matching pattern and replace matching patterns log.info('Updating file: %s...', file_path) for line in fileinput.input(file_path, inplace=True): if re.search(pattern, line): log.info('Updating line: %s', line) new_line = re.sub(pattern, replace_str, line, count=g) log.info('Replacing with line: %s', new_line) sys.stdout.write(new_line) else: sys.stdout.write(line)
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L583-L627
replace in file
python
def replace_lines_in_files(search_string, replacement_line): """ Finds lines containing the search string and replaces the whole line with the specified replacement string. """ # have the user select some files paths = _s.dialogs.MultipleFiles('DIS AND DAT|*.*') if paths == []: return for path in paths: _shutil.copy(path, path+".backup") lines = read_lines(path) for n in range(0,len(lines)): if lines[n].find(search_string) >= 0: print(lines[n]) lines[n] = replacement_line.strip() + "\n" write_to_file(path, join(lines, '')) return
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_functions.py#L1264-L1284
replace in file
python
def apply_replacements(cfile, replacements): """Applies custom replacements. mapping(dict), where each dict contains: 'match' - filename match pattern to check against, the filename replacement is applied. 'replacement' - string used to replace the matched part of the filename 'is_regex' - if True, the pattern is treated as a regex. If False, simple substring check is used (if 'match' in filename). Default is False 'with_extension' - if True, the file extension is not included in the pattern matching. Default is False Example replacements:: {'match': ':', 'replacement': '-', 'is_regex': False, 'with_extension': False, } :param str cfile: name of a file :param list replacements: mapping(dict) filename pattern matching directives :returns: formatted filename :rtype: str """ if not replacements: return cfile for rep in replacements: if not rep.get('with_extension', False): # By default, preserve extension cfile, cext = os.path.splitext(cfile) else: cfile = cfile cext = '' if 'is_regex' in rep and rep['is_regex']: cfile = re.sub(rep['match'], rep['replacement'], cfile) else: cfile = cfile.replace(rep['match'], rep['replacement']) # Rejoin extension (cext might be empty-string) cfile = cfile + cext return cfile
https://github.com/shad7/tvrenamer/blob/7fb59cb02669357e73b7acb92dcb6d74fdff4654/tvrenamer/core/formatter.py#L53-L102
replace in file
python
def replace_lines(html_file, transformed): """Replace lines in the old file with the transformed lines.""" result = [] with codecs.open(html_file, 'r', 'utf-8') as input_file: for line in input_file: # replace all single quotes with double quotes line = re.sub(r'\'', '"', line) for attr, value, new_link in transformed: if attr in line and value in line: # replace old link with new staticfied link new_line = line.replace(value, new_link) result.append(new_line) break else: result.append(line) return ''.join(result)
https://github.com/danidee10/Staticfy/blob/ebc555b00377394b0f714e4a173d37833fec90cb/staticfy/staticfy.py#L92-L111
replace in file
python
def substitute(search, replace, text): 'Regex substitution function. Replaces regex ``search`` with ``replace`` in ``text``' return re.sub(re.compile(str(search)), replace, text)
https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/contrib/regex.py#L12-L14
replace in file
python
def str_replace(x, pat, repl, n=-1, flags=0, regex=False): """Replace occurences of a pattern/regex in a column with some other string. :param str pattern: string or a regex pattern :param str replace: a replacement string :param int n: number of replacements to be made from the start. If -1 make all replacements. :param int flags: ?? :param bool regex: If True, ...? :returns: an expression containing the string replacements. Example: >>> import vaex >>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.'] >>> df = vaex.from_arrays(text=text) >>> df # text 0 Something 1 very pretty 2 is coming 3 our 4 way. >>> df.text.str.replace(pat='et', repl='__') Expression = str_replace(text, pat='et', repl='__') Length: 5 dtype: str (expression) --------------------------------- 0 Som__hing 1 very pr__ty 2 is coming 3 our 4 way. """ sl = _to_string_sequence(x).replace(pat, repl, n, flags, regex) return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/functions.py#L1113-L1147
replace in file
python
def replace(s, pattern, replacement): """Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression. Args: s (str): the string to modify pattern (str): the search expression replacement (str): the string to replace each match with """ # the replacement string may contain invalid backreferences (like \1 or \g) # which will cause python's regex to blow up. Since this should emulate # the jam version exactly and the jam version didn't support # backreferences, this version shouldn't either. re.sub # allows replacement to be a callable; this is being used # to simply return the replacement string and avoid the hassle # of worrying about backreferences within the string. def _replacement(matchobj): return replacement return re.sub(pattern, _replacement, s)
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/regex.py#L31-L50
replace in file
python
def xml_replace(filename, **replacements): """Read the content of an XML template file (XMLT), apply the given `replacements` to its substitution markers, and write the result into an XML file with the same name but ending with `xml` instead of `xmlt`. First, we write an XMLT file, containing a regular HTML comment, a readily defined element `e1`, and some other elements with substitutions markers. Substitution markers are HTML comments starting and ending with the `|` character: >>> from hydpy import xml_replace, TestIO >>> with TestIO(): ... with open('test1.xmlt', 'w') as templatefile: ... _ = templatefile.write( ... '<!--a normal comment-->\\n' ... '<e1>element 1</e1>\\n' ... '<e2><!--|e2|--></e2>\\n' ... '<e3><!--|e3_|--></e3>\\n' ... '<e4><!--|e4=element 4|--></e4>\\n' ... '<e2><!--|e2|--></e2>') Function |xml_replace| can both be called within a Python session and from a command line. We start with the first type of application. Each substitution marker must be met by a keyword argument unless it holds a default value (`e4`). All arguments are converted to a |str| object (`e3`). Template files can use the same substitution marker multiple times (`e2`): >>> with TestIO(): ... xml_replace('test1', e2='E2', e3_=3, e4='ELEMENT 4') template file: test1.xmlt target file: test1.xml replacements: e2 --> E2 (given argument) e3_ --> 3 (given argument) e4 --> ELEMENT 4 (given argument) e2 --> E2 (given argument) >>> with TestIO(): ... with open('test1.xml') as targetfile: ... print(targetfile.read()) <!--a normal comment--> <e1>element 1</e1> <e2>E2</e2> <e3>3</e3> <e4>ELEMENT 4</e4> <e2>E2</e2> Without custom values, |xml_replace| applies predefined default values, if available (`e4`): >>> with TestIO(): ... xml_replace('test1', e2='E2', e3_=3) # doctest: +ELLIPSIS template file: test1.xmlt target file: test1.xml replacements: e2 --> E2 (given argument) e3_ --> 3 (given argument) e4 --> element 4 (default argument) e2 --> E2 (given argument) >>> with TestIO(): ... with open('test1.xml') as targetfile: ... print(targetfile.read()) <!--a normal comment--> <e1>element 1</e1> <e2>E2</e2> <e3>3</e3> <e4>element 4</e4> <e2>E2</e2> Missing and useless keyword arguments result in errors: >>> with TestIO(): ... xml_replace('test1', e2='E2') Traceback (most recent call last): ... RuntimeError: While trying to replace the markers `e2, e3_, and e4` \ of the XML template file `test1.xmlt` with the available keywords `e2`, \ the following error occurred: Marker `e3_` cannot be replaced. >>> with TestIO(): ... xml_replace('test1', e2='e2', e3_='E3', e4='e4', e5='e5') Traceback (most recent call last): ... RuntimeError: While trying to replace the markers `e2, e3_, and e4` \ of the XML template file `test1.xmlt` with the available keywords `e2, e3_, \ e4, and e5`, the following error occurred: Keyword(s) `e5` cannot be used. Using different default values for the same substitution marker is not allowed: >>> from hydpy import pub, TestIO, xml_replace >>> with TestIO(): ... with open('test2.xmlt', 'w') as templatefile: ... _ = templatefile.write( ... '<e4><!--|e4=element 4|--></e4>\\n' ... '<e4><!--|e4=ELEMENT 4|--></e4>') >>> with TestIO(): ... xml_replace('test2', e4=4) template file: test2.xmlt target file: test2.xml replacements: e4 --> 4 (given argument) e4 --> 4 (given argument) >>> with TestIO(): ... with open('test2.xml') as targetfile: ... print(targetfile.read()) <e4>4</e4> <e4>4</e4> >>> with TestIO(): ... xml_replace('test2') Traceback (most recent call last): ... RuntimeError: Template file `test2.xmlt` defines different default values \ for marker `e4`. As mentioned above, function |xml_replace| is registered as a "script function" and can thus be used via command line: >>> pub.scriptfunctions['xml_replace'].__name__ 'xml_replace' >>> pub.scriptfunctions['xml_replace'].__module__ 'hydpy.exe.replacetools' Use script |hyd| to execute function |xml_replace|: >>> from hydpy import run_subprocess >>> with TestIO(): ... run_subprocess( ... 'hyd.py xml_replace test1 e2="Element 2" e3_=3') template file: test1.xmlt target file: test1.xml replacements: e2 --> Element 2 (given argument) e3_ --> 3 (given argument) e4 --> element 4 (default argument) e2 --> Element 2 (given argument) >>> with TestIO(): ... with open('test1.xml') as targetfile: ... print(targetfile.read()) <!--a normal comment--> <e1>element 1</e1> <e2>Element 2</e2> <e3>3</e3> <e4>element 4</e4> <e2>Element 2</e2> """ keywords = set(replacements.keys()) templatename = f'{filename}.xmlt' targetname = f'{filename}.xml' print(f'template file: {templatename}') print(f'target file: {targetname}') print('replacements:') with open(templatename) as templatefile: templatebody = templatefile.read() parts = templatebody.replace('<!--|', '|-->').split('|-->') defaults = {} for idx, part in enumerate(parts): if idx % 2: subparts = part.partition('=') if subparts[2]: parts[idx] = subparts[0] if subparts[0] not in replacements: if ((subparts[0] in defaults) and (defaults[subparts[0]] != str(subparts[2]))): raise RuntimeError( f'Template file `{templatename}` defines ' f'different default values for marker ' f'`{subparts[0]}`.') defaults[subparts[0]] = str(subparts[2]) markers = parts[1::2] try: unused_keywords = keywords.copy() for idx, part in enumerate(parts): if idx % 2: argument_info = 'given argument' newpart = replacements.get(part) if newpart is None: argument_info = 'default argument' newpart = defaults.get(part) if newpart is None: raise RuntimeError( f'Marker `{part}` cannot be replaced.') print(f' {part} --> {newpart} ({argument_info})') parts[idx] = str(newpart) unused_keywords.discard(part) targetbody = ''.join(parts) if unused_keywords: raise RuntimeError( f'Keyword(s) `{objecttools.enumeration(unused_keywords)}` ' f'cannot be used.') with open(targetname, 'w') as targetfile: targetfile.write(targetbody) except BaseException: objecttools.augment_excmessage( f'While trying to replace the markers ' f'`{objecttools.enumeration(sorted(set(markers)))}` of the ' f'XML template file `{templatename}` with the available ' f'keywords `{objecttools.enumeration(sorted(keywords))}`')
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/exe/replacetools.py#L9-L211
replace in file
python
def replace(document, search, replace): """ Replace all occurences of string with a different string, return updated document """ newdocument = document searchre = re.compile(search) for element in newdocument.iter(): if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements if element.text: if searchre.search(element.text): element.text = re.sub(search, replace, element.text) return newdocument
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L629-L641
replace in file
python
def replace_ext(file_path, new_ext): """ >>> replace_ext('one/two/three.four.doc', '.html') 'one/two/three.four.html' >>> replace_ext('one/two/three.four.DOC', '.html') 'one/two/three.four.html' >>> replace_ext('one/two/three.four.DOC', 'html') 'one/two/three.four.html' """ if not new_ext.startswith(os.extsep): new_ext = os.extsep + new_ext index = file_path.rfind(os.extsep) return file_path[:index] + new_ext
https://github.com/PolicyStat/docx2html/blob/2dc4afd1e3a3f2f0b357d0bff903eb58bcc94429/docx2html/core.py#L34-L46
replace in file
python
def _replace(expr, pat, repl, n=-1, case=True, flags=0, regex=True): """ Replace occurrence of pattern/regex in the sequence or scalar with some other string. Equivalent to str.replace() :param expr: :param pat: Character sequence or regular expression :param repl: Replacement :param n: Number of replacements to make from start :param case: if True, case sensitive :param flags: re module flag, e.g. re.IGNORECASE :return: sequence or scalar """ return _string_op(expr, Replace, _pat=pat, _repl=repl, _n=n, _case=case, _flags=flags, _regex=regex)
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/strings.py#L405-L420
replace in file
python
def replace_argument(script, from_, to): """Replaces command line argument.""" replaced_in_the_end = re.sub(u' {}$'.format(re.escape(from_)), u' {}'.format(to), script, count=1) if replaced_in_the_end != script: return replaced_in_the_end else: return script.replace( u' {} '.format(from_), u' {} '.format(to), 1)
https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/utils.py#L131-L139
replace in file
python
def replace(self, seq): ''' Performs search and replace on the given input string `seq` using the values stored in this trie. This method uses a O(n**2) chart-parsing algorithm to find the optimal way of replacing matches in the input. Arguments: - `seq`: ''' # #1: seq must be stored in a container with a len() function seq = list(seq) # chart is a (n-1) X (n) table # chart[0] represents all matches of length (0+1) = 1 # chart[n-1] represents all matches/rewrites of length (n-1+1) = n # chart[0][0] represents a match of length 1 starting at character 0 # chart[0][n-1] represents a match of length 1 starting at character n-1 # cells in the chart are tuples: # (score, list) # we initialise chart by filling in row 0: # each cell gets assigned (0, char), where char is the character at # the corresponding position in the input string chart = [ [None for _i in range(len(seq)) ] for _i in range(len(seq)) ] chart[0] = [(0, char) for char in seq] # now we fill in the chart using the results from the aho-corasick # string matches for (begin, length, value) in self.find_all(seq): chart[length-1][begin] = (length, value) # now we need to fill in the chart row by row, starting with row 1 for row in range(1, len(chart)): # each row is 1 cell shorter than the last for col in range(len(seq) - row): # the entry in [row][col] is the choice with the highest score; to # find this, we must search the possible partitions of the cell # # things on row 2 have only one possible partition: 1 + 1 # things on row 3 have two: 1 + 2, 2 + 1 # things on row 4 have three: 1+3, 3+1, 2+2 # # we assume that any pre-existing entry found by aho-corasick # in a cell is already optimal #print('scanning [{}][{}]'.format(row, col)) if chart[row][col] is not None: continue # chart[1][2] is the cell of matches of length 2 starting at # character position 2; # it can only be composed of chart[0][2] + chart[0][3] # # partition_point is the length of the first of the two parts # of the cell #print('cell[{}][{}] => '.format(row, col)) best_score = -1 best_value = None for partition_point in range(row): # the two cells will be [partition_point][col] and # [row - partition_point - 2][col+partition_point+1] x1 = partition_point y1 = col x2 = row - partition_point - 1 y2 = col + partition_point + 1 #print(' [{}][{}] + [{}][{}]'.format(x1, y1, x2, y2)) s1, v1 = chart[x1][y1] s2, v2 = chart[x2][y2] # compute the score score = s1 + s2 #print(' = {} + {}'.format((s1, v1), (s2, v2))) #print(' = score {}'.format(score)) if best_score < score: best_score = score best_value = v1 + v2 chart[row][col] = (best_score, best_value) #print(' sets new best score with value {}'.format( # best_value)) # now the optimal solution is stored at the top of the chart return chart[len(seq)-1][0][1]
https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L264-L338
replace in file
python
def regex_replace(regex, repl, text): r""" thin wrapper around re.sub regex_replace MULTILINE and DOTALL are on by default in all util_regex functions Args: regex (str): pattern to find repl (str): replace pattern with this text (str): text to modify Returns: str: modified text Example1: >>> # ENABLE_DOCTEST >>> from utool.util_regex import * # NOQA >>> regex = r'\(.*\):' >>> repl = '(*args)' >>> text = '''def foo(param1, ... param2, ... param3):''' >>> result = regex_replace(regex, repl, text) >>> print(result) def foo(*args) Example2: >>> # ENABLE_DOCTEST >>> from utool.util_regex import * # NOQA >>> import utool as ut >>> regex = ut.named_field_regex([('keyword', 'def'), ' ', ('funcname', '.*'), '\(.*\):']) >>> repl = ut.named_field_repl([('funcname',), ('keyword',)]) >>> text = '''def foo(param1, ... param2, ... param3):''' >>> result = regex_replace(regex, repl, text) >>> print(result) foodef """ return re.sub(regex, repl, text, **RE_KWARGS)
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_regex.py#L203-L243
replace in file
python
def line(state, host, name, line, present=True, replace=None, flags=None): ''' Ensure lines in files using grep to locate and sed to replace. + name: target remote file to edit + line: string or regex matching the target line + present: whether the line should be in the file + replace: text to replace entire matching lines when ``present=True`` + flags: list of flags to pass to sed when replacing/deleting Regex line matching: Unless line matches a line (starts with ^, ends $), pyinfra will wrap it such that it does, like: ``^.*LINE.*$``. This means we don't swap parts of lines out. To change bits of lines, see ``files.replace``. Regex line escaping: If matching special characters (eg a crontab line containing *), remember to escape it first using Python's ``re.escape``. ''' match_line = line # Ensure we're matching a whole ^line$ if not match_line.startswith('^'): match_line = '^.*{0}'.format(match_line) if not match_line.endswith('$'): match_line = '{0}.*$'.format(match_line) # Is there a matching line in this file? present_lines = host.fact.find_in_file(name, match_line) # If replace present, use that over the matching line if replace: line = replace # We must provide some kind of replace to sed_replace_command below else: replace = '' # Save commands for re-use in dynamic script when file not present at fact stage echo_command = 'echo "{0}" >> {1}'.format(line, name) sed_replace_command = sed_replace( name, match_line, replace, flags=flags, ) # No line and we want it, append it if not present_lines and present: # If the file does not exist - it *might* be created, so we handle it # dynamically with a little script. if present_lines is None: yield ''' # If the file now exists if [ -f "{target}" ]; then # Grep for the line, sed if matches (grep "{match_line}" "{target}" && {sed_replace_command}) || \ # Else echo {echo_command} # No file, just echo else {echo_command} fi '''.format( target=name, match_line=match_line, echo_command=echo_command, sed_replace_command=sed_replace_command, ) # Otherwise the file exists and there is no matching line, so append it else: yield echo_command # Line(s) exists and we want to remove them, replace with nothing elif present_lines and not present: yield sed_replace(name, match_line, '', flags=flags) # Line(s) exists and we have want to ensure they're correct elif present_lines and present: # If any of lines are different, sed replace them if replace and any(line != replace for line in present_lines): yield sed_replace_command
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/modules/files.py#L83-L165
replace in file
python
def replace(pretty, old_str, new_str): """ Replace strings giving some info on where the replacement was done """ out_str = '' line_number = 1 changes = 0 for line in pretty.splitlines(keepends=True): new_line = line.replace(old_str, new_str) if line.find(old_str) != -1: logging.debug('%s', line_number) logging.debug('< %s', line) logging.debug('> %s', new_line) changes += 1 out_str += new_line line_number += 1 logging.info('Total changes(%s): %s', old_str, changes) return out_str
https://github.com/chaoss/grimoirelab-sigils/blob/33d395195acb316287143a535a2c6e4009bf0528/src/migration/utils.py#L40-L58
replace in file
python
def copy_or_replace(src, dst): '''try to copy with mode, and if it fails, try replacing ''' try: shutil.copy(src, dst) except (OSError, IOError), e: # It's possible that the file existed, but was owned by someone # else - in that situation, shutil.copy might then fail when it # tries to copy perms. # However, it's possible that we have write perms to the dir - # in which case, we can just delete and replace import errno if e.errno == errno.EPERM: import tempfile # try copying into a temporary location beside the old # file - if we have perms to do that, we should have perms # to then delete the old file, and move the new one into # place if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) dst_dir, dst_name = os.path.split(dst) dst_temp = tempfile.mktemp(prefix=dst_name + '.', dir=dst_dir) shutil.copy(src, dst_temp) if not os.path.isfile(dst_temp): raise RuntimeError( "shutil.copy completed successfully, but path" " '%s' still did not exist" % dst_temp) os.remove(dst) shutil.move(dst_temp, dst)
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L317-L347
replace in file
python
def _find_and_replace(text, start_string, end_string, replace_fn): """Remove everything found between instances of start_string and end_string. Replace each such instance with replace_fn(removed_text) e.g. _find_and_replace(u"the [[fat]] cat [[sat]]", u"[[", u"]]", lambda x: x) = u"the fat cat sat" Args: text: a unicode string start_string: a unicode string end_string: a unicode string replace_fn: a unary function from unicode string to unicode string Returns: a string """ ret = u"" current_pos = 0 while True: start_pos = text.find(start_string, current_pos) if start_pos == -1: ret += text[current_pos:] break ret += text[current_pos:start_pos] end_pos = text.find(end_string, start_pos + len(start_string)) if end_pos == -1: break ret += replace_fn(text[start_pos + len(start_string):end_pos]) current_pos = end_pos + len(end_string) return ret
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wiki.py#L309-L339
replace in file
python
def regex_replace(txt, rgx, val, ignorecase=False, multiline=False): r''' Searches for a pattern and replaces with a sequence of characters. .. code-block:: jinja {% set my_text = 'lets replace spaces' %} {{ my_text | regex_replace('\s+', '__') }} will be rendered as: .. code-block:: text lets__replace__spaces ''' flag = 0 if ignorecase: flag |= re.I if multiline: flag |= re.M compiled_rgx = re.compile(rgx, flag) return compiled_rgx.sub(val, txt)
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L411-L432
replace in file
python
def _writeReplacementFiles(self, session, directory, name): """ Write the replacement files """ if self.replaceParamFile: self.replaceParamFile.write(session=session, directory=directory, name=name) if self.replaceValFile: self.replaceValFile.write(session=session, directory=directory, name=name)
https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/prj.py#L1763-L1773
replace in file
python
def in_place( self, mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None, ): """ A context in which a file may be re-written in-place with new content. Yields a tuple of :samp:`({readable}, {writable})` file objects, where `writable` replaces `readable`. If an exception occurs, the old file is restored, removing the written data. Mode *must not* use ``'w'``, ``'a'``, or ``'+'``; only read-only-modes are allowed. A :exc:`ValueError` is raised on invalid modes. For example, to add line numbers to a file:: p = Path(filename) assert p.isfile() with p.in_place() as (reader, writer): for number, line in enumerate(reader, 1): writer.write('{0:3}: '.format(number))) writer.write(line) Thereafter, the file at `filename` will have line numbers in it. """ import io if set(mode).intersection('wa+'): raise ValueError('Only read-only file modes can be used') # move existing file to backup, create new file with same permissions # borrowed extensively from the fileinput module backup_fn = self + (backup_extension or os.extsep + 'bak') try: os.unlink(backup_fn) except os.error: pass os.rename(self, backup_fn) readable = io.open( backup_fn, mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) try: perm = os.fstat(readable.fileno()).st_mode except OSError: writable = open( self, 'w' + mode.replace('r', ''), buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) else: os_mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC if hasattr(os, 'O_BINARY'): os_mode |= os.O_BINARY fd = os.open(self, os_mode, perm) writable = io.open( fd, "w" + mode.replace('r', ''), buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) try: if hasattr(os, 'chmod'): os.chmod(self, perm) except OSError: pass try: yield readable, writable except Exception: # move backup back readable.close() writable.close() try: os.unlink(self) except os.error: pass os.rename(backup_fn, self) raise else: readable.close() writable.close() finally: try: os.unlink(backup_fn) except os.error: pass
https://github.com/jaraco/path.py/blob/bbe7d99e7a64a004f866ace9ec12bd9b296908f5/path/__init__.py#L1336-L1424
replace in file
python
def replace(s, old, new, maxreplace=-1): """replace (str, old, new[, maxreplace]) -> string Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, only the first maxreplace occurrences are replaced. """ return s.replace(old, new, maxreplace)
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/string.py#L526-L534
replace in file
python
def myreplace(astr, thefind, thereplace): """in string astr replace all occurences of thefind with thereplace""" alist = astr.split(thefind) new_s = alist.split(thereplace) return new_s
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/EPlusInterfaceFunctions/mylib2.py#L296-L300
replace in file
python
def patchFile(filename, replacements): """ Applies the supplied list of replacements to a file """ patched = Utility.readFile(filename) # Perform each of the replacements in the supplied dictionary for key in replacements: patched = patched.replace(key, replacements[key]) Utility.writeFile(filename, patched)
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/Utility.py#L42-L52
replace in file
python
def _apply_replacement(error, found_file, file_lines): """Apply a single replacement.""" fixed_lines = file_lines fixed_lines[error[1].line - 1] = error[1].replacement concatenated_fixed_lines = "".join(fixed_lines) # Only fix one error at a time found_file.seek(0) found_file.write(concatenated_fixed_lines) found_file.truncate()
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/linter.py#L632-L641
replace in file
python
def replace(self, src: str) -> str: """ Extends LaTeX syntax via regex preprocess :param src: str LaTeX string :return: str New LaTeX string """ if not self.readied: self.ready() # Brackets + simple pre replacements: src = self._dict_replace(self.simple_pre, src) # Superscripts and subscripts + pre regexps: for regex, replace in self.regex_pre: src = regex.sub(replace, src) # Unary and binary operators: src = self._operators_replace(src) # Loop regexps: src_prev = src for i in range(self.max_iter): for regex, replace in self.loop_regexps: src = regex.sub(replace, src) if src_prev == src: break else: src_prev = src # Post regexps: for regex, replace in self.regex_post: src = regex.sub(replace, src) # Simple post replacements: src = self._dict_replace(self.simple_post, src) # Escape characters: src = self.escapes_regex.sub(r'\1', src) return src
https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_filter.py#L863-L904
replace in file
python
def replace_ext(file_path, ext): ''' Change extension of a file_path to something else (provide None to remove) ''' if not file_path: raise Exception("File path cannot be empty") dirname = os.path.dirname(file_path) filename = FileHelper.getfilename(file_path) if ext: filename = filename + '.' + ext return os.path.join(dirname, filename)
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L509-L517
replace in file
python
def replace(self, nodes): """ Replaces user defined files search pattern occurrences with replacement pattern using given nodes. :param nodes: Nodes. :type nodes: list :return: Method success. :rtype: bool """ files = {} for node in nodes: if node.family == "SearchFile": files[node.file] = node.children elif node.family == "SearchOccurence": file = node.parent.file if not file in files: files[file] = [] files[file].append(node) replacement_pattern = self.Replace_With_comboBox.currentText() SearchAndReplace.insert_pattern(replacement_pattern, self.__replace_with_patterns_model) replace_results = {} for file, occurrences in files.iteritems(): editor = self.__container.get_editor(file) if editor: document = editor.document() else: cache_data = self.__files_cache.get_content(file) if cache_data is None: LOGGER.warning( "!> {0} | '{1}' file doesn't exists in files cache!".format(self.__class__.__name__, file)) continue content = self.__files_cache.get_content(file).content document = self.__get_document(content) self.__cache(file, content, document) replace_results[file] = self.__replace_within_document(document, occurrences, replacement_pattern) self.set_replace_results(replace_results) self.__container.engine.notifications_manager.notify( "{0} | '{1}' pattern occurence(s) replaced in '{2}' files!".format(self.__class__.__name__, sum(replace_results.values()), len(replace_results.keys())))
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/search_in_files.py#L1359-L1403
replace in file
python
def sed(filename, before, after, flags='g'): """ Search and replaces the given pattern on filename. :param filename: relative or absolute file path. :param before: expression to be replaced (see 'man sed') :param after: expression to replace with (see 'man sed') :param flags: sed-compatible regex flags in example, to make the search and replace case insensitive, specify ``flags="i"``. The ``g`` flag is always specified regardless, so you do not need to remember to include it when overriding this parameter. :returns: If the sed command exit code was zero then return, otherwise raise CalledProcessError. """ expression = r's/{0}/{1}/{2}'.format(before, after, flags) return subprocess.check_call(["sed", "-i", "-r", "-e", expression, os.path.expanduser(filename)])
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/files.py#L24-L43
replace in file
python
def replace(name, repl, full_match=False): ''' Replace all instances of a string or full line in the running config name String to replace repl The replacement text full_match Whether `name` will match the full line or only a subset of the line. Defaults to False. When False, .* is added around `name` for matching in the `show run` config. Examples: .. code-block:: yaml replace snmp string: onyx.replace: - name: randoSNMPstringHERE - repl: NEWrandoSNMPstringHERE replace full snmp string: onyx.replace: - name: ^snmp-server community randoSNMPstringHERE group network-operator$ - repl: snmp-server community NEWrandoSNMPstringHERE group network-operator - full_match: True .. note:: The first example will replace the SNMP string on both the group and the ACL, so you will not lose the ACL setting. Because the second is an exact match of the line, when the group is removed, the ACL is removed, but not readded, because it was not matched. ''' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} if full_match is False: search = '^.*{0}.*$'.format(name) else: search = name matches = __salt__['onyx.cmd']('find', search) if not matches: ret['result'] = True ret['comment'] = 'Nothing found to replace' return ret if __opts__['test'] is True: ret['result'] = None ret['comment'] = 'Configs will be changed' ret['changes']['old'] = matches ret['changes']['new'] = [re.sub(name, repl, match) for match in matches] return ret ret['changes'] = __salt__['onyx.cmd']('replace', name, repl, full_match=full_match) matches = __salt__['onyx.cmd']('find', search) if matches: ret['result'] = False ret['comment'] = 'Failed to replace all instances of "{0}"'.format(name) else: ret['result'] = True ret['comment'] = 'Successfully replaced all instances of "{0}" with "{1}"'.format(name, repl) return ret
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/onyx.py#L307-L379
replace in file
python
def replace(self, photo, photo_file, **kwds): """ Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace an existing photo. """ with open(photo_file, 'rb') as in_file: result = self._client.post("/photo/%s/replace.json" % self._extract_id(photo), files={'photo': in_file}, **kwds)["result"] return Photo(self._client, result)
https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/api/api_photo.py#L85-L96
replace in file
python
def __replace_all(repls: dict, input: str) -> str: """ Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply the replacements; :return: *(str)* the string with the desired characters replaced """ return re.sub('|'.join(re.escape(key) for key in repls.keys()), lambda k: repls[k.group(0)], input)
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/automata_IO.py#L12-L23
replace in file
python
def replace(self): """ Used to replace a matched string with another. :return: The data after replacement. :rtype: str """ if self.replace_with: # pylint: disable=no-member return substrings( self.regex, self.replace_with, # pylint: disable=no-member self.data, self.occurences, # pylint: disable=no-member ) return self.data
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/helpers.py#L1049-L1065
replace in file
python
def multiple_replace(string, replacements): # type: (str, Dict[str,str]) -> str """Simultaneously replace multiple strigns in a string Args: string (str): Input string replacements (Dict[str,str]): Replacements dictionary Returns: str: String with replacements """ pattern = re.compile("|".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL) return pattern.sub(lambda x: replacements[x.group(0)], string)
https://github.com/OCHA-DAP/hdx-python-utilities/blob/9c89e0aa5afac2c002b02a2d8f0e5b91eeb3d2a3/src/hdx/utilities/text.py#L9-L22
replace in file
python
def bytes_replace(byte_str, start_idx, stop_idx, replacement): """ Replaces given portion of the byte string with the replacement, returns new array :param byte_str: :param start_idx: :param stop_idx: :param replacement: :return: """ return byte_str[:start_idx] + replacement + byte_str[stop_idx:]
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/crypto_util.py#L157-L166
replace in file
python
def _string_replace(arg, pattern, replacement): """ Replaces each exactly occurrence of pattern with given replacement string. Like Python built-in str.replace Parameters ---------- pattern : string replacement : string Examples -------- >>> import ibis >>> table = ibis.table([('strings', 'string')]) >>> result = table.strings.replace('aaa', 'foo') # 'aaabbbaaa' becomes 'foobbbfoo' # noqa: E501 Returns ------- replaced : string """ return ops.StringReplace(arg, pattern, replacement).to_expr()
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L2258-L2278
replace in file
python
def replace(self, text): """Do j/v replacement""" for (pattern, repl) in self.patterns: text = re.subn(pattern, repl, text)[0] return text
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/latin/j_v.py#L18-L22
replace in file
python
def replace_version_string(content, variable, new_version): """ Given the content of a file, finds the version string and updates it. :param content: The file contents :param variable: The version variable name as a string :param new_version: The new version number as a string :return: A string with the updated version number """ return re.sub( r'({0} ?= ?["\'])\d+\.\d+(?:\.\d+)?(["\'])'.format(variable), r'\g<1>{0}\g<2>'.format(new_version), content )
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/history/__init__.py#L109-L122
replace in file
python
def replace_name(file_path, new_name): ''' Change the file name in a path but keep the extension ''' if not file_path: raise Exception("File path cannot be empty") elif not new_name: raise Exception("New name cannot be empty") dirname = os.path.dirname(file_path) ext = os.path.splitext(os.path.basename(file_path))[1] return os.path.join(dirname, new_name + ext)
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/leutile.py#L520-L528
replace in file
python
def _replace_words(replacements, string): """Replace words with corresponding values in replacements dict. Words must be separated by spaces or newlines. """ output_lines = [] for line in string.split('\n'): output_words = [] for word in line.split(' '): new_word = replacements.get(word, word) output_words.append(new_word) output_lines.append(output_words) return '\n'.join(' '.join(output_words) for output_words in output_lines)
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/ui/emoticon.py#L9-L21
replace in file
python
def replace(self, name, newname): """ Replace all occurrences of name with newname """ if not re.match("[a-zA-Z]\w*", name): return None if not re.match("[a-zA-Z]\w*", newname): return None def _replace(match): return match.group(0).replace(match.group('name'), newname) pattern = re.compile("(\W|^)(?P<name>" + name + ")(\W|$)") cut = re.sub(pattern, _replace, str(self)) return Cut(cut)
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/tree/cut.py#L273-L287
replace in file
python
def replace(old_value, new_value, full_match=False): ''' Replace string or full line matches in switch's running config If full_match is set to True, then the whole line will need to be matched as part of the old value. .. code-block:: bash salt '*' onyx.cmd replace 'TESTSTRINGHERE' 'NEWTESTSTRINGHERE' ''' if full_match is False: matcher = re.compile('^.*{0}.*$'.format(re.escape(old_value)), re.MULTILINE) repl = re.compile(re.escape(old_value)) else: matcher = re.compile(old_value, re.MULTILINE) repl = re.compile(old_value) lines = {'old': [], 'new': []} for line in matcher.finditer(show_run()): lines['old'].append(line.group(0)) lines['new'].append(repl.sub(new_value, line.group(0))) delete_config(lines['old']) add_config(lines['new']) return lines
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/onyx.py#L463-L489
replace in file
python
def find_one_and_replace(self, filter, replacement, projection=None, sort=None, upsert=False, return_document=ReturnDocument.BEFORE, **kwargs): """Finds a single document and replaces it, returning either the original or the replaced document. The :meth:`find_one_and_replace` method differs from :meth:`find_one_and_update` by replacing the document matched by *filter*, rather than modifying the existing document. >>> for doc in db.test.find({}): ... print(doc) ... {u'x': 1, u'_id': 0} {u'x': 1, u'_id': 1} {u'x': 1, u'_id': 2} >>> db.test.find_one_and_replace({'x': 1}, {'y': 1}) {u'x': 1, u'_id': 0} >>> for doc in db.test.find({}): ... print(doc) ... {u'y': 1, u'_id': 0} {u'x': 1, u'_id': 1} {u'x': 1, u'_id': 2} :Parameters: - `filter`: A query that matches the document to replace. - `replacement`: The replacement document. - `projection` (optional): A list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If `projection` is a list "_id" will always be returned. Use a mapping to exclude fields from the result (e.g. projection={'_id': False}). - `sort` (optional): a list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is replaced. - `upsert` (optional): When ``True``, inserts a new document if no document matches the query. Defaults to ``False``. - `return_document`: If :attr:`ReturnDocument.BEFORE` (the default), returns the original document before it was replaced, or ``None`` if no document matches. If :attr:`ReturnDocument.AFTER`, returns the replaced or inserted document. - `**kwargs` (optional): additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions). .. versionchanged:: 3.4 Added the `collation` option. .. versionchanged:: 3.2 Respects write concern. .. warning:: Starting in PyMongo 3.2, this command uses the :class:`~pymongo.write_concern.WriteConcern` of this :class:`~pymongo.collection.Collection` when connected to MongoDB >= 3.2. Note that using an elevated write concern with this command may be slower compared to using the default write concern. .. versionadded:: 3.0 """ common.validate_ok_for_replace(replacement) kwargs['update'] = replacement return self.__find_and_modify(filter, projection, sort, upsert, return_document, **kwargs)
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/collection.py#L2293-L2357
replace in file
python
def replace_some(ol,value,*indexes,**kwargs): ''' from elist.elist import * ol = [1,'a',3,'a',5,'a',6,'a'] id(ol) new = replace_some(ol,'AAA',1,3,7) ol new id(ol) id(new) #### ol = [1,'a',3,'a',5,'a',6,'a'] id(ol) rslt = replace_some(ol,'AAA',1,3,7,mode="original") ol rslt id(ol) id(rslt) ''' if('mode' in kwargs): mode = kwargs["mode"] else: mode = "new" indexes = list(indexes) return(replace_seqs(ol,value,indexes,mode=mode))
https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L5055-L5079
replace in file
python
def regex_replace(arg, pattern, replacement): """ Replaces match found by regex with replacement string. Replacement string can also be a regex Parameters ---------- pattern : string (regular expression string) replacement : string (can be regular expression string) Examples -------- >>> import ibis >>> table = ibis.table([('strings', 'string')]) >>> result = table.strings.replace('(b+)', r'<\1>') # 'aaabbbaa' becomes 'aaa<bbb>aaa' # noqa: E501 Returns ------- modified : string """ return ops.RegexReplace(arg, pattern, replacement).to_expr()
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L2235-L2255
replace in file
python
def advReplace(document, search, replace, bs=3): """ Replace all occurences of string with a different string, return updated document This is a modified version of python-docx.replace() that takes into account blocks of <bs> elements at a time. The replace element can also be a string or an xml etree element. What it does: It searches the entire document body for text blocks. Then scan thos text blocks for replace. Since the text to search could be spawned across multiple text blocks, we need to adopt some sort of algorithm to handle this situation. The smaller matching group of blocks (up to bs) is then adopted. If the matching group has more than one block, blocks other than first are cleared and all the replacement text is put on first block. Examples: original text blocks : [ 'Hel', 'lo,', ' world!' ] search / replace: 'Hello,' / 'Hi!' output blocks : [ 'Hi!', '', ' world!' ] original text blocks : [ 'Hel', 'lo,', ' world!' ] search / replace: 'Hello, world' / 'Hi!' output blocks : [ 'Hi!!', '', '' ] original text blocks : [ 'Hel', 'lo,', ' world!' ] search / replace: 'Hel' / 'Hal' output blocks : [ 'Hal', 'lo,', ' world!' ] @param instance document: The original document @param str search: The text to search for (regexp) @param mixed replace: The replacement text or lxml.etree element to append, or a list of etree elements @param int bs: See above @return instance The document with replacement applied """ # Enables debug output DEBUG = False newdocument = document # Compile the search regexp searchre = re.compile(search) # Will match against searchels. Searchels is a list that contains last # n text elements found in the document. 1 < n < bs searchels = [] for element in newdocument.iter(): if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements if element.text: # Add this element to searchels searchels.append(element) if len(searchels) > bs: # Is searchels is too long, remove first elements searchels.pop(0) # Search all combinations, of searchels, starting from # smaller up to bigger ones # l = search lenght # s = search start # e = element IDs to merge found = False for l in range(1, len(searchels)+1): if found: break #print "slen:", l for s in range(len(searchels)): if found: break if s+l <= len(searchels): e = range(s, s+l) #print "elems:", e txtsearch = '' for k in e: txtsearch += searchels[k].text # Searcs for the text in the whole txtsearch match = searchre.search(txtsearch) if match: found = True # I've found something :) if DEBUG: log.debug("Found element!") log.debug("Search regexp: %s", searchre.pattern) log.debug("Requested replacement: %s", replace) log.debug("Matched text: %s", txtsearch) log.debug("Matched text (splitted): %s", map(lambda i: i.text, searchels)) log.debug("Matched at position: %s", match.start()) log.debug("matched in elements: %s", e) if isinstance(replace, etree._Element): log.debug("Will replace with XML CODE") elif isinstance(replace(list, tuple)): log.debug("Will replace with LIST OF" " ELEMENTS") else: log.debug("Will replace with:", re.sub(search, replace, txtsearch)) curlen = 0 replaced = False for i in e: curlen += len(searchels[i].text) if curlen > match.start() and not replaced: # The match occurred in THIS element. # Puth in the whole replaced text if isinstance(replace, etree._Element): # Convert to a list and process # it later replace = [replace] if isinstance(replace, (list, tuple)): # I'm replacing with a list of # etree elements # clear the text in the tag and # append the element after the # parent paragraph # (because t elements cannot have # childs) p = findTypeParent( searchels[i], '{%s}p' % nsprefixes['w']) searchels[i].text = re.sub( search, '', txtsearch) insindex = p.getparent().index(p)+1 for r in replace: p.getparent().insert( insindex, r) insindex += 1 else: # Replacing with pure text searchels[i].text = re.sub( search, replace, txtsearch) replaced = True log.debug( "Replacing in element #: %s", i) else: # Clears the other text elements searchels[i].text = '' return newdocument
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L759-L907
replace in file
python
def replace(self, resource, id_, document): """Replace document in index.""" args = self._es_args(resource, refresh=True) document.pop('_id', None) document.pop('_type', None) self._update_parent_args(resource, args, document) return self.elastic(resource).index(body=document, id=id_, **args)
https://github.com/petrjasek/eve-elastic/blob/f146f31b348d22ac5559cf78717b3bb02efcb2d7/eve_elastic/elastic.py#L659-L665
replace in file
python
def _tab_newline_replace(self,fromlines,tolines): """Returns from/to line lists with tabs expanded and newlines removed. Instead of tab characters being replaced by the number of spaces needed to fill in to the next tab stop, this function will fill the space with tab characters. This is done so that the difference algorithms can identify changes in a file when tabs are replaced by spaces and vice versa. At the end of the HTML generation, the tab characters will be replaced with a nonbreakable space. """ def expand_tabs(line): # hide real spaces line = line.replace(' ','\0') # expand tabs into spaces line = line.expandtabs(self._tabsize) # replace spaces from expanded tabs back into tab characters # (we'll replace them with markup after we do differencing) line = line.replace(' ','\t') return line.replace('\0',' ').rstrip('\n') fromlines = [expand_tabs(line) for line in fromlines] tolines = [expand_tabs(line) for line in tolines] return fromlines,tolines
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/difflib.py#L1810-L1831
replace in file
python
def replace(self, re_text, replace_str, text): """ 正则表达式替换 :param re_text: 正则表达式 :param replace_str: 替换字符串 :param text: 搜索文档 :return: 替换后的字符串 """ return re.sub(re_text, replace_str, text)
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/html_parserlib.py#L53-L61
replace in file
python
def do_file_sub(self, srcpath, regexp, subst): '''Apply a regexp substitution to a file archived by sosreport. srcpath is the path in the archive where the file can be found. regexp can be a regexp string or a compiled re object. subst is a string to replace each occurance of regexp in the content of srcpath. This function returns the number of replacements made. ''' try: path = self._get_dest_for_srcpath(srcpath) self._log_debug("substituting scrpath '%s'" % srcpath) self._log_debug("substituting '%s' for '%s' in '%s'" % (subst, regexp, path)) if not path: return 0 readable = self.archive.open_file(path) content = readable.read() if not isinstance(content, six.string_types): content = content.decode('utf8', 'ignore') result, replacements = re.subn(regexp, subst, content) if replacements: self.archive.add_string(result, srcpath) else: replacements = 0 except (OSError, IOError) as e: # if trying to regexp a nonexisting file, dont log it as an # error to stdout if e.errno == errno.ENOENT: msg = "file '%s' not collected, substitution skipped" self._log_debug(msg % path) else: msg = "regex substitution failed for '%s' with: '%s'" self._log_error(msg % (path, e)) replacements = 0 return replacements
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L482-L516
replace in file
python
def sub(pattern, repl, string, *args, **kwargs): """Apply `sub` after applying backrefs.""" flags = args[4] if len(args) > 4 else kwargs.get('flags', 0) is_replace = _is_replace(repl) is_string = isinstance(repl, (str, bytes)) if is_replace and repl.use_format: raise ValueError("Compiled replace cannot be a format object!") pattern = compile_search(pattern, flags) return _re.sub( pattern, (compile_replace(pattern, repl) if is_replace or is_string else repl), string, *args, **kwargs )
https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/bre.py#L419-L431
replace in file
python
def replace(self, photo_file, **kwds): """ Endpoint: /photo/<id>/replace.json Uploads the specified photo file to replace this photo. """ result = self._client.photo.replace(self, photo_file, **kwds) self._replace_fields(result.get_fields())
https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/objects/photo.py#L32-L39
replace in file
python
def replace(path, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, backup='.bak', dry_run=False, search_only=False, show_changes=True, ignore_if_missing=False, preserve_inode=True, backslash_literal=False, ): ''' .. versionadded:: 0.17.0 Replace occurrences of a pattern in a file. If ``show_changes`` is ``True``, then a diff of what changed will be returned, otherwise a ``True`` will be returned when changes are made, and ``False`` when no changes are made. This is a pure Python implementation that wraps Python's :py:func:`~re.sub`. path Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`~re.search`. repl The replacement text count : 0 Maximum number of pattern occurrences to be replaced. If count is a positive integer ``n``, only ``n`` occurrences will be replaced, otherwise all occurrences will be replaced. flags (list or int) A list of flags defined in the ``re`` module documentation from the Python standard library. Each list item should be a string that will correlate to the human-friendly flag name. E.g., ``['IGNORECASE', 'MULTILINE']``. Optionally, ``flags`` may be an int, with a value corresponding to the XOR (``|``) of all the desired flags. Defaults to 8 (which supports 'MULTILINE'). bufsize (int or str) How much of the file to buffer into memory at once. The default value ``1`` processes one line at a time. The special value ``file`` may be specified which will read the entire file into memory before processing. append_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True``, and pattern is not found, then the content will be appended to the file. prepend_if_not_found : False .. versionadded:: 2014.7.0 If set to ``True`` and pattern is not found, then the content will be prepended to the file. not_found_content .. versionadded:: 2014.7.0 Content to use for append/prepend if not found. If None (default), uses ``repl``. Useful when ``repl`` uses references to group in pattern. backup : .bak The file extension to use for a backup of the file before editing. Set to ``False`` to skip making a backup. dry_run : False If set to ``True``, no changes will be made to the file, the function will just return the changes that would have been made (or a ``True``/``False`` value if ``show_changes`` is set to ``False``). search_only : False If set to true, this no changes will be performed on the file, and this function will simply return ``True`` if the pattern was matched, and ``False`` if not. show_changes : True If ``True``, return a diff of changes made. Otherwise, return ``True`` if changes were made, and ``False`` if not. .. note:: Using this option will store two copies of the file in memory (the original version and the edited version) in order to generate the diff. This may not normally be a concern, but could impact performance if used with large files. ignore_if_missing : False .. versionadded:: 2015.8.0 If set to ``True``, this function will simply return ``False`` if the file doesn't exist. Otherwise, an error will be thrown. preserve_inode : True .. versionadded:: 2015.8.0 Preserve the inode of the file, so that any hard links continue to share the inode with the original filename. This works by *copying* the file, reading from the copy, and writing to the file at the original inode. If ``False``, the file will be *moved* rather than copied, and a new file will be written to a new inode, but using the original filename. Hard links will then share an inode with the backup, instead (if using ``backup`` to create a backup copy). backslash_literal : False .. versionadded:: 2016.11.7 Interpret backslashes as literal backslashes for the repl and not escape characters. This will help when using append/prepend so that the backslashes are not interpreted for the repl on the second run of the state. If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' file.replace /path/to/file pattern='=' repl=':' salt '*' file.replace /path/to/file pattern="bind-address\\s*=" repl='bind-address:' CLI Examples: .. code-block:: bash salt '*' file.replace /etc/httpd/httpd.conf pattern='LogLevel warn' repl='LogLevel info' salt '*' file.replace /some/file pattern='before' repl='after' flags='[MULTILINE, IGNORECASE]' ''' symlink = False if is_link(path): symlink = True target_path = os.readlink(path) given_path = os.path.expanduser(path) path = os.path.realpath(os.path.expanduser(path)) if not os.path.exists(path): if ignore_if_missing: return False else: raise SaltInvocationError('File not found: {0}'.format(path)) if not __utils__['files.is_text'](path): raise SaltInvocationError( 'Cannot perform string replacements on a binary file: {0}' .format(path) ) if search_only and (append_if_not_found or prepend_if_not_found): raise SaltInvocationError( 'search_only cannot be used with append/prepend_if_not_found' ) if append_if_not_found and prepend_if_not_found: raise SaltInvocationError( 'Only one of append and prepend_if_not_found is permitted' ) flags_num = _get_flags(flags) cpattern = re.compile(salt.utils.stringutils.to_bytes(pattern), flags_num) filesize = os.path.getsize(path) if bufsize == 'file': bufsize = filesize # Search the file; track if any changes have been made for the return val has_changes = False orig_file = [] # used for show_changes and change detection new_file = [] # used for show_changes and change detection if not salt.utils.platform.is_windows(): pre_user = get_user(path) pre_group = get_group(path) pre_mode = salt.utils.files.normalize_mode(get_mode(path)) # Avoid TypeErrors by forcing repl to be bytearray related to mmap # Replacement text may contains integer: 123 for example repl = salt.utils.stringutils.to_bytes(six.text_type(repl)) if not_found_content: not_found_content = salt.utils.stringutils.to_bytes(not_found_content) found = False temp_file = None content = salt.utils.stringutils.to_unicode(not_found_content) \ if not_found_content and (prepend_if_not_found or append_if_not_found) \ else salt.utils.stringutils.to_unicode(repl) try: # First check the whole file, determine whether to make the replacement # Searching first avoids modifying the time stamp if there are no changes r_data = None # Use a read-only handle to open the file with salt.utils.files.fopen(path, mode='rb', buffering=bufsize) as r_file: try: # mmap throws a ValueError if the file is empty. r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) except (ValueError, mmap.error): # size of file in /proc is 0, but contains data r_data = salt.utils.stringutils.to_bytes("".join(r_file)) if search_only: # Just search; bail as early as a match is found if re.search(cpattern, r_data): return True # `with` block handles file closure else: return False else: result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) # found anything? (even if no change) if nrepl > 0: found = True # Identity check the potential change has_changes = True if pattern != repl else has_changes if prepend_if_not_found or append_if_not_found: # Search for content, to avoid pre/appending the # content if it was pre/appended in a previous run. if re.search(salt.utils.stringutils.to_bytes('^{0}($|(?=\r\n))'.format(re.escape(content))), r_data, flags=flags_num): # Content was found, so set found. found = True orig_file = r_data.read(filesize).splitlines(True) \ if isinstance(r_data, mmap.mmap) \ else r_data.splitlines(True) new_file = result.splitlines(True) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to open file '{0}'. " "Exception: {1}".format(path, exc) ) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() if has_changes and not dry_run: # Write the replacement text in this block. try: # Create a copy to read from and to use as a backup later temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) r_data = None try: # Open the file in write mode with salt.utils.files.fopen(path, mode='w', buffering=bufsize) as w_file: try: # Open the temp file in read mode with salt.utils.files.fopen(temp_file, mode='r', buffering=bufsize) as r_file: r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn(cpattern, repl.replace('\\', '\\\\') if backslash_literal else repl, r_data, count) try: w_file.write(salt.utils.stringutils.to_str(result)) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to write file '{0}'. Contents may " "be truncated. Temporary file contains copy " "at '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) finally: if r_data and isinstance(r_data, mmap.mmap): r_data.close() except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) if not found and (append_if_not_found or prepend_if_not_found): if not_found_content is None: not_found_content = repl if prepend_if_not_found: new_file.insert(0, not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) else: # append_if_not_found # Make sure we have a newline at the end of the file if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) has_changes = True if not dry_run: try: # Create a copy to read from and for later use as a backup temp_file = _mkstemp_copy(path=path, preserve_inode=preserve_inode) except (OSError, IOError) as exc: raise CommandExecutionError("Exception: {0}".format(exc)) # write new content in the file while avoiding partial reads try: fh_ = salt.utils.atomicfile.atomic_open(path, 'wb') for line in new_file: fh_.write(salt.utils.stringutils.to_bytes(line)) finally: fh_.close() if backup and has_changes and not dry_run: # keep the backup only if it was requested # and only if there were any changes backup_name = '{0}{1}'.format(path, backup) try: shutil.move(temp_file, backup_name) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to move the temp file '{0}' to the " "backup file '{1}'. " "Exception: {2}".format(path, temp_file, exc) ) if symlink: symlink_backup = '{0}{1}'.format(given_path, backup) target_backup = '{0}{1}'.format(target_path, backup) # Always clobber any existing symlink backup # to match the behaviour of the 'backup' option try: os.symlink(target_backup, symlink_backup) except OSError: os.remove(symlink_backup) os.symlink(target_backup, symlink_backup) except Exception: raise CommandExecutionError( "Unable create backup symlink '{0}'. " "Target was '{1}'. " "Exception: {2}".format(symlink_backup, target_backup, exc) ) elif temp_file: try: os.remove(temp_file) except (OSError, IOError) as exc: raise CommandExecutionError( "Unable to delete temp file '{0}'. " "Exception: {1}".format(temp_file, exc) ) if not dry_run and not salt.utils.platform.is_windows(): check_perms(path, None, pre_user, pre_group, pre_mode) differences = __utils__['stringutils.get_diff'](orig_file, new_file) if show_changes: return differences # We may have found a regex line match but don't need to change the line # (for situations where the pattern also matches the repl). Revert the # has_changes flag to False if the final result is unchanged. if not differences: has_changes = False return has_changes
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L2071-L2450
replace in file
python
def sed(path, before, after, limit='', backup='.bak', options='-r -e', flags='g', escape_all=False, negate_match=False): ''' .. deprecated:: 0.17.0 Use :py:func:`~salt.modules.file.replace` instead. Make a simple edit to a file Equivalent to: .. code-block:: bash sed <backup> <options> "/<limit>/ s/<before>/<after>/<flags> <file>" path The full path to the file to be edited before A pattern to find in order to replace with ``after`` after Text that will replace ``before`` limit : ``''`` An initial pattern to search for before searching for ``before`` backup : ``.bak`` The file will be backed up before edit with this file extension; **WARNING:** each time ``sed``/``comment``/``uncomment`` is called will overwrite this backup options : ``-r -e`` Options to pass to sed flags : ``g`` Flags to modify the sed search; e.g., ``i`` for case-insensitive pattern matching negate_match : False Negate the search command (``!``) .. versionadded:: 0.17.0 Forward slashes and single quotes will be escaped automatically in the ``before`` and ``after`` patterns. CLI Example: .. code-block:: bash salt '*' file.sed /etc/httpd/httpd.conf 'LogLevel warn' 'LogLevel info' ''' # Largely inspired by Fabric's contrib.files.sed() # XXX:dc: Do we really want to always force escaping? # path = os.path.expanduser(path) if not os.path.exists(path): return False # Mandate that before and after are strings before = six.text_type(before) after = six.text_type(after) before = _sed_esc(before, escape_all) after = _sed_esc(after, escape_all) limit = _sed_esc(limit, escape_all) if sys.platform == 'darwin': options = options.replace('-r', '-E') cmd = ['sed'] cmd.append('-i{0}'.format(backup) if backup else '-i') cmd.extend(salt.utils.args.shlex_split(options)) cmd.append( r'{limit}{negate_match}s/{before}/{after}/{flags}'.format( limit='/{0}/ '.format(limit) if limit else '', negate_match='!' if negate_match else '', before=before, after=after, flags=flags ) ) cmd.append(path) return __salt__['cmd.run_all'](cmd, python_shell=False)
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L1049-L1132
replace in file
python
def replace_in_dirs(version): """Look through dirs and run replace_in_files in each.""" print(color( "Upgrading directory-components dependency in all repos...", fg='blue', style='bold')) for dirname in Utils.dirs: replace = "directory-components=={}".format(version) replace_in_files(dirname, replace) done(version)
https://github.com/uktrade/directory-components/blob/305b3cfd590e170255503ae3c41aebcaa658af8e/scripts/upgrade_header_footer.py#L59-L67
replace in file
python
def replace_suffixes_4(self, word): """ Perform replacements on even more common suffixes. """ length = len(word) replacements = {'ational': 'ate', 'tional': 'tion', 'alize': 'al', 'icate': 'ic', 'iciti': 'ic', 'ical': 'ic', 'ful': '', 'ness': ''} for suffix in replacements.keys(): if word.endswith(suffix): suffix_length = len(suffix) if self.r1 <= (length - suffix_length): word = word[:-suffix_length] + replacements[suffix] if word.endswith('ative'): if self.r1 <= (length - 5) and self.r2 <= (length - 5): word = word[:-5] return word
https://github.com/evandempsey/porter2-stemmer/blob/949824b7767c25efb014ef738e682442fa70c10b/porter2stemmer/porter2stemmer.py#L274-L293
replace in file
python
def replace(s, replace): """Replace multiple values in a string""" for r in replace: s = s.replace(*r) return s
https://github.com/dbcli/cli_helpers/blob/3ebd891ac0c02bad061182dbcb54a47fb21980ae/cli_helpers/utils.py#L64-L68
replace in file
python
def replace_file_or_dir(dest, source): """Replace `dest` with `source`. Acts like an `os.rename` if `dest` does not exist. Otherwise, `dest` is deleted and `src` is renamed to `dest`. """ from rez.vendor.atomicwrites import replace_atomic if not os.path.exists(dest): try: os.rename(source, dest) return except: if not os.path.exists(dest): raise try: replace_atomic(source, dest) return except: pass with make_tmp_name(dest) as tmp_dest: os.rename(dest, tmp_dest) os.rename(source, dest)
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L223-L247
replace in file
python
def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined that the files differ. ''' old_isbin = not __utils__['files.is_text'](old) new_isbin = not __utils__['files.is_text'](new) if any((old_isbin, new_isbin)): if all((old_isbin, new_isbin)): return 'Replace binary file' elif old_isbin: return 'Replace binary file with text file' elif new_isbin: return 'Replace text file with binary file' return ''
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/file.py#L112-L131
replace in file
python
def replace(self, target): """ Rename this path to the given path, clobbering the existing destination if it exists. """ if sys.version_info < (3, 3): raise NotImplementedError("replace() is only available " "with Python 3.3 and later") if self._closed: self._raise_closed() self._accessor.replace(self, target)
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pathlib2/__init__.py#L1520-L1530
replace in file
python
def replace(self, ): """Replace the current reftrack :returns: None :rtype: None :raises: None """ tfi = self.get_taskfileinfo_selection() if tfi: self.reftrack.replace(tfi)
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/reftrackwidget.py#L402-L411
replace in file
python
def replace(self, target): """ Rename this path to the given path, clobbering the existing destination if it exists. """ if sys.version_info < (3, 3): raise NotImplementedError("replace() is only available " "with Python 3.3 and later") self._accessor.replace(self, target)
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1152-L1160
replace in file
python
def doc_replace(match, sphinx_docs): """Convert Sphinx ``:doc:`` to plain reST link. Args: match (_sre.SRE_Match): A match (from ``re``) to be used in substitution. sphinx_docs (list): List to be track the documents that have been encountered. Returns: str: The ``match`` converted to a link. """ sphinx_docs.append(match.group("path")) return "`{}`_".format(match.group("value"))
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L229-L242
replace in file
python
def replace_rep_after(text: str) -> str: "Replace repetitions at the character level in `text` after the repetition" def _replace_rep(m): c, cc = m.groups() return f"{c}{TK_REP}{len(cc)+1}" re_rep = re.compile(r"(\S)(\1{2,})") return re_rep.sub(_replace_rep, text)
https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/ulmfit/__init__.py#L78-L87
replace in file
python
def replace(text, old, new, count=None, strip=False): ''' Replace an ``old`` subset of ``text`` with ``new``. ``old`` type may be either a string or regular expression. If ``strip``, remove all leading/trailing whitespace. If ``count``, replace the specified number of occurence, otherwise replace all. ''' if is_string(old): text = text.replace(old, new, -1 if count is None else count) else: text = old.sub(new, text, 0 if count is None else count) if strip: text = text.strip(None if strip == True else strip) return text
https://github.com/dakrauth/strutil/blob/c513645a919488d9b22ab612a539773bef866f10/strutil.py#L25-L43
replace in file
python
def replace(value, arg): """ Replaces one string with another in a given string usage: {{ foo|replace:"aaa|xxx"}} """ replacement = arg.split('|') try: return value.replace(replacement[0], replacement[1]) except: return value
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/formatting.py#L12-L22
replace in file
python
def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): r""" Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to :meth:`str.replace` or :func:`re.sub`. Parameters ---------- pat : str or compiled regex String can be a character sequence or regular expression. .. versionadded:: 0.20.0 `pat` also accepts a compiled regex. repl : str or callable Replacement string or a callable. The callable is passed the regex match object and must return a replacement string to be used. See :func:`re.sub`. .. versionadded:: 0.20.0 `repl` also accepts a callable. n : int, default -1 (all) Number of replacements to make from start. case : bool, default None - If True, case sensitive (the default if `pat` is a string) - Set to False for case insensitive - Cannot be set if `pat` is a compiled regex flags : int, default 0 (no flags) - re module flags, e.g. re.IGNORECASE - Cannot be set if `pat` is a compiled regex regex : bool, default True - If True, assumes the passed-in pattern is a regular expression. - If False, treats the pattern as a literal string - Cannot be set to False if `pat` is a compiled regex or `repl` is a callable. .. versionadded:: 0.23.0 Returns ------- Series or Index of object A copy of the object with all matching occurrences of `pat` replaced by `repl`. Raises ------ ValueError * if `regex` is False and `repl` is a callable or `pat` is a compiled regex * if `pat` is a compiled regex and `case` or `flags` is set Notes ----- When `pat` is a compiled regex, all flags should be included in the compiled regex. Use of `case`, `flags`, or `regex=False` with a compiled regex will raise an error. Examples -------- When `pat` is a string and `regex` is True (the default), the given `pat` is compiled as a regex. When `repl` is a string, it replaces matching regex patterns as with :meth:`re.sub`. NaN value(s) in the Series are left as is: >>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f.', 'ba', regex=True) 0 bao 1 baz 2 NaN dtype: object When `pat` is a string and `regex` is False, every `pat` is replaced with `repl` as with :meth:`str.replace`: >>> pd.Series(['f.o', 'fuz', np.nan]).str.replace('f.', 'ba', regex=False) 0 bao 1 fuz 2 NaN dtype: object When `repl` is a callable, it is called on every `pat` using :func:`re.sub`. The callable should expect one positional argument (a regex object) and return a string. To get the idea: >>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f', repr) 0 <_sre.SRE_Match object; span=(0, 1), match='f'>oo 1 <_sre.SRE_Match object; span=(0, 1), match='f'>uz 2 NaN dtype: object Reverse every lowercase alphabetic word: >>> repl = lambda m: m.group(0)[::-1] >>> pd.Series(['foo 123', 'bar baz', np.nan]).str.replace(r'[a-z]+', repl) 0 oof 123 1 rab zab 2 NaN dtype: object Using regex groups (extract second group and swap case): >>> pat = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)" >>> repl = lambda m: m.group('two').swapcase() >>> pd.Series(['One Two Three', 'Foo Bar Baz']).str.replace(pat, repl) 0 tWO 1 bAR dtype: object Using a compiled regex with flags >>> import re >>> regex_pat = re.compile(r'FUZ', flags=re.IGNORECASE) >>> pd.Series(['foo', 'fuz', np.nan]).str.replace(regex_pat, 'bar') 0 foo 1 bar 2 NaN dtype: object """ # Check whether repl is valid (GH 13438, GH 15055) if not (is_string_like(repl) or callable(repl)): raise TypeError("repl must be a string or callable") is_compiled_re = is_re(pat) if regex: if is_compiled_re: if (case is not None) or (flags != 0): raise ValueError("case and flags cannot be set" " when pat is a compiled regex") else: # not a compiled regex # set default case if case is None: case = True # add case flag, if provided if case is False: flags |= re.IGNORECASE if is_compiled_re or len(pat) > 1 or flags or callable(repl): n = n if n >= 0 else 0 compiled = re.compile(pat, flags=flags) f = lambda x: compiled.sub(repl=repl, string=x, count=n) else: f = lambda x: x.replace(pat, repl, n) else: if is_compiled_re: raise ValueError("Cannot use a compiled regex as replacement " "pattern with regex=False") if callable(repl): raise ValueError("Cannot use a callable replacement when " "regex=False") f = lambda x: x.replace(pat, repl, n) return _na_map(f, arr)
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/strings.py#L423-L578
replace in file
python
def replace(self, key, content, **metadata): """ :param key: Document unique identifier. :param str content: Content to store and index for search. :param metadata: Arbitrary key/value pairs to store for document. Update the given document. Existing metadata will not be removed and replaced with the provided metadata. """ self.remove(key) self.add(key, content, **metadata)
https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/fts.py#L96-L106