10 examples of 'how to find a string in a text file using python' in Python

Every line of 'how to find a string in a text file using python' 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

453def read_python_source(file):
454 with open(file, 'rb') as fd:
455 data = fd.read()
456 if PY3:
457 data = decode_source(data)
458 return data
94def get_file(file_name):
95 return ''.join(get_file_lines(file_name))
29def read_text_file(filename, encoding="utf-8"):
30 """
31 Reads a file under python3 with encoding (default UTF-8).
32 Also works under python2, without encoding.
33 Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp)
34 principle.
35 """
36 try:
37 with open(filename, 'r', encoding) as f:
38 r = f.read()
39 except TypeError:
40 with open(filename, 'r') as f:
41 r = f.read()
42 return r
18def prepare_file(text):
19 if _python2:
20 result = IOModule('my file contents')
21 else:
22 result = IOModule(b'my file contents')
23
24 return result
69def get_text(path):
70 with io.open(path, mode='r', encoding='utf-8-sig', newline=None) as f:
71 return f.read()
239def read_file(path):
240 if path == '-':
241 lines = sys.stdin.readlines()
242 else:
243 try:
244 f = open(path)
245 except IOError as msg:
246 print('open %s: %s' % (path, msg), file=sys.stderr)
247 sys.exit(1)
248 lines = f.readlines()
249 f.close()
250
251 return ''.join(lines)
72def read_source(filename: str):
73 """Treat *source* as a filename or a string with content."""
74 return pathlib.Path(filename).read_text(encoding='utf-8')
5def load_text(path):
6 with open(path, 'r', encoding = 'utf8') as f:
7 text = f.read().strip()
8 return text
39def _load_text(text_path):
40 with open(text_path + '.txt', 'r', encoding='utf-8') as fin:
41 text = ' '.join([line.strip() for line in fin.readlines()])
42 return text

Related snippets