10 examples of 'how to open text file in python' in Python

Every line of 'how to open text file in 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
17def open_python_file(filename):
18 """Open a read-only Python file taking proper care of its encoding.
19
20 In Python 3, we would like all files to be opened with utf-8 encoding.
21 However, some author like to specify PEP263 headers in their source files
22 with their own encodings. In that case, we should respect the author's
23 encoding.
24 """
25 import tokenize
26
27 if hasattr(tokenize, "open"): # Added in Python 3.2
28 # Open file respecting PEP263 encoding. If no encoding header is
29 # found, opens as utf-8.
30 return tokenize.open(filename)
31 else:
32 return open(filename, "r")
49def open_source_file(filename):
50 with open(filename, "rb") as byte_stream:
51 encoding = detect_encoding(byte_stream.readline)[0]
52 stream = open(filename, "r", newline=None, encoding=encoding)
53 data = stream.read()
54 return stream, encoding, data
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
26def open_file(file_path):
27 global file
28 file = open(file_path, 'wb')
29 reset()
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
47def open_source_file(filename):
48 with open(filename, 'rb') as byte_stream:
49 encoding = detect_encoding(byte_stream.readline)[0]
50 stream = open(filename, 'r', newline=None, encoding=encoding)
51 try:
52 data = stream.read()
53 except UnicodeError: # wrong encoding
54 # detect_encoding returns utf-8 if no encoding specified
55 msg = 'Wrong (%s) or no encoding specified' % encoding
56 raise exceptions.AstroidBuildingException(msg)
57 return stream, encoding, data
104def open_file(self):
105 self.f = codecs.open(self.path, "w", encoding='utf-8')
212def open(self, event=None):
213 '''
214 Open given file
215 '''
216 with open(self.file.path, encoding='UTF-8') as file:
217 file_text = file.read()
218 if file_text:
219 self.modified_event_triggered_by_opening_file = True
220 self.insert(tk.END, file_text)
50def new_file(self):
51 pass

Related snippets