4 examples of 'python find string in file' in Python

Every line of 'python find 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
77def _find_line(string, file_name):
78 """
79 find the first occurence of a string in a file
80 """
81
82 with open(file_name, 'r') as fi:
83 for line in fi:
84 if string in line:
85 return line
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

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)
648def look_up_string(self, string_index):
649 """Looks up the specified string index in this PEX file's string
650 table."""
651 self.read_pex_file(up_to='string_table')
652 return self.string_table.stored_strings[string_index].str_val
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)

Related snippets