10 examples of 'python open file if exists' in Python

Every line of 'python open file if exists' 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
26def open_file(file_path):
27 global file
28 file = open(file_path, 'wb')
29 reset()
4def try_open(filename, mode):
5 for each in codecs:
6 try:
7 return open(filename, mode, encoding=each)
8 except UnicodeDecodeError:
9 continue
10 raise UnicodeDecodeError
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")
81def open(filename, mode, *args):
82 mode = mode.replace('U', '')
83 return _open(filename, mode, *args, errors='ignore')
27def _open_file(filename):
28 if sys.platform == "win32":
29 os.startfile(filename)
30 else:
31 if sys.platform == "darwin":
32 opener = "open"
33 else:
34 opener = "xdg-open"
35 subprocess.call([opener, filename])
20def open(file, mode=None, encoding=None):
21 if mode is None:
22 mode = 'r'
23
24 if '/' in file:
25 if 'w' or 'a' in mode:
26 path_dir = os.path.dirname(file)
27 if not os.path.isdir(path_dir):
28 os.makedirs(path_dir)
29
30 f = builtins.open(file, mode=mode, encoding=encoding)
31 return f
249def myopen(filename, mode="r"):
250 if "w" in mode:
251 ensure_dir(filename)
252 return open(filename, mode)
99def file_open(*args, **kwargs):
100 """Open file
101
102 see built-in open() documentation for more details
103
104 Note: The reason this is kept in a separate module is to easily
105 be able to provide a stub module that doesn't alter system
106 state at all (for unit tests)
107 """
108 return open(*args, **kwargs)
27def file_exists( pathname ):
28 """checks that a given file exists"""
29 result = 1
30 try:
31 file = open( pathname, "r" )
32 file.close()
33 except:
34 result = None
35 sys.stderr.write( pathname + " couldn't be accessed\n" )
36
37 return result
433def _open_file(self, module_name):
434 module_json_cache = self.module_json_cache
435 if module_name in module_json_cache:
436 for file_name in module_json_cache[module_name]["files"]:
437 if os.path.isfile(file_name) and not file_name.endswith("-meta.xml"):
438 self.window.open_file(file_name)

Related snippets