10 examples of 'python replace string in file' in Python

Every line of 'python replace string in file' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
14def replace_in_file(filename, search, replace):
15 # Read in the file
16 filedata = None
17 with open(filename, 'r') as file :
18 filedata = file.read()
19
20 # Replace the target string
21 filedata = filedata.replace(search, replace)
22
23 # Write the file out again
24 with open(filename, 'w') as file:
25 file.write(filedata)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

27def replace(file, pattern, subst):
28 # Read contents from file as a single string
29 file_handle = open(file, 'r')
30 file_string = file_handle.read()
31 file_handle.close()
32
33 # Use RE package to allow for replacement (also allowing for (multiline) REGEX)
34 file_string = (re.sub(pattern, subst, file_string))
35
36 # Write contents to file.
37 # Using mode 'w' truncates the file.
38 file_handle = open(file, 'w')
39 file_handle.write(file_string)
40 file_handle.close()
5def replace_in_file(file_path, search, replace):
6 with open(file_path, "r") as handle:
7 content = handle.read()
8 if search not in content:
9 raise Exception("Incorrect development version in conans/__init__.py")
10 content = content.replace(search, replace)
11 content = content.encode("utf-8")
12 with open(file_path, "wb") as handle:
13 handle.write(content)
64def file_substitute(filename, search, replace):
65 f = open(filename, 'r')
66 file_data = f.read()
67 f.close()
68 new_data = file_data.replace(search, replace)
69 f = open(filename, 'w')
70 f.write(new_data)
71 f.close()
3def applyReplacesOnFile(fileName, replaces, write=True):
4 with open(fileName) as f:
5 content = f.read()
6
7 for r in replaces:
8 content = content.replace(r, replaces[r])
9 if write:
10 with open(fileName, "w") as f:
11 f.write(content)
12 else:
13 return content
194def replace(string, old, new):
195 return string.replace(old, new)
291def fileStringReplace(fn, src, dst):
292 if MLABFileManager.exists(fn):
293 lines = [];
294 with open(fn, 'r') as f:
295 for l in f:
296 lines += [l.replace(src, dst)];
297 with open(fn, 'w') as f:
298 for l in lines:
299 f.write(l);
300 else :
301 print "Error: could not open file for replacement, " + fn;
17def replace_in_file(workspace, src_file_path, from_str, to_str):
18 """Replace from_str with to_str in the name and content of the given file.
19
20 If any edits were necessary, returns the new filename (which may be the same as the old filename).
21 """
22 from_bytes = from_str.encode('ascii')
23 to_bytes = to_str.encode('ascii')
24 data = read_file(os.path.join(workspace, src_file_path), binary_mode=True)
25 if from_bytes not in data and from_str not in src_file_path:
26 return None
27
28 dst_file_path = src_file_path.replace(from_str, to_str)
29 safe_file_dump(os.path.join(workspace, dst_file_path),
30 data.replace(from_bytes, to_bytes),
31 mode='wb')
32 if src_file_path != dst_file_path:
33 os.unlink(os.path.join(workspace, src_file_path))
34 return dst_file_path
85def replace_contents(file_path, regex, new_content):
86 with open(file_path, 'r+') as f:
87 content = f.read()
88 content = regex.sub(new_content, content)
89 f.seek(0)
90 f.write(content)
189def replace(data):
190 left_angle = 'dsfw4rwfdfstg43'
191 right_angle = '3dsdtgsgt43trfdf'
192 data = data.replace('\<', left_angle).replace('\>', right_angle)
193 # 正则匹配出 data 中所有 <> 中的变量,返回列表
194 keys = re.findall(r'<(.*?)>', data)
195 _vars = {}
196
197 for k in keys:
198 k = k.replace(left_angle, '<').replace(right_angle, '>')
199 # 正则匹配出 k 中的 + - ** * // / % , ( ) 返回列表
200 values = re.split(r'(\+|-|\*\*|\*|//|/|%|,|\(|\))', k)
201 for v in values:
202 #切片操作处理,正则匹配出 [] 中内容
203 s = v.split('[', 1)
204 index = ''
205 if len(s) == 2:
206 v = s[0]
207 index = '[' + s[1]
208
209 if v in g.var and v not in _vars:
210 # 如果在 var 中是 list
211 if isinstance(g.var[v], list) and not index:
212 # 是测试数据文件中的值,则 pop 第一个值
213 if len(g.var[v]) == 0:
214 raise Exception('The key:%s is no value in data csv' %v)
215 elif len(g.var[v]) == 1:
216 _vars[v] = g.var[v][0]
217 g.var['_last_'] = True
218 else:
219 _vars[v] = g.var[v].pop(0)
220
221 else:
222 _vars[v] = g.var[v]
223
224 try:
225 value = eval(k, globals(), _vars)
226 except:
227 value = '<' + k + '>'
228
229 if data == '<' + keys[0] + '>':
230 data = value
231 # 否则需要替换,此时变量强制转换为为字符串
232 else:
233 data = data.replace('<' + k + '>', str(value))
234 data = data.replace(left_angle, '<').replace(right_angle, '>')
235 return data

Related snippets