Skip to content
Snippets Groups Projects
Commit 5d499abf authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

add default to read_in_file

parent 7ce5172f
No related branches found
No related tags found
No related merge requests found
# v2.9.7
* add binary shift operations to `AtomicNumber`
* add `default` to `read_in_file`
__version__ = '2.9.7_a2'
__version__ = '2.9.7'
......@@ -81,19 +81,32 @@ def write_to_file(path: str, data: tp.Union[bytes, str],
file.close()
def read_in_file(path: str, encoding: tp.Optional[str] = None) -> tp.Union[bytes, str]:
def read_in_file(path: str, encoding: tp.Optional[str] = None,
default: tp.Optional[tp.Union[bytes, str]] = None) -> tp.Union[bytes, str]:
"""
Opens a file for reading, reads it in, converts to given encoding (or returns as bytes
if not given), and closes it.
:param path: path of file to read
:param encoding: optional encoding. If default (None given), this will be returned as bytes
:param default: value to return when the file does not exist. Default (None) will raise a
FileNotFoundError
:return: file content, either decoded as a str, or not as bytes
"""
if encoding is None:
file = open(path, 'rb')
else:
file = codecs.open(path, 'rb', encoding)
if os.path.isdir(path):
if default:
return default
raise FileNotFoundError('%s found and is a directory' % (path, ))
try:
if encoding is None:
file = open(path, 'rb')
else:
file = codecs.open(path, 'rb', encoding)
except FileNotFoundError:
if default:
return default
raise
try:
return file.read()
......
......@@ -14,6 +14,14 @@ def putfile(path: str) -> None:
class TestFiles(unittest.TestCase):
def try_directory(self):
os.system('mkdir test')
self.assertRaises(FileNotFoundError, lambda: read_in_file('test'))
self.assertEqual(b'test', read_in_file('test', default=b'test'))
os.system('rm -rf test')
self.assertRaises(FileNotFoundError, lambda: read_in_file('test'))
self.assertEqual(b'test', read_in_file('test', default=b'test'))
def test_make_noncolliding_name(self):
with open('test.txt', 'w') as f_out:
f_out.write('test')
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment