diff options
author | robot-piglet <[email protected]> | 2025-03-17 20:53:16 +0300 |
---|---|---|
committer | robot-piglet <[email protected]> | 2025-03-17 21:03:50 +0300 |
commit | 1a33d7680ad2188c1116a53b49c9f704d3c08652 (patch) | |
tree | 517559262d145233883830c295f171053be7701e /library/python | |
parent | 3e6e38fbbb98346c3621b5bb4960ce1a34efa9a2 (diff) |
Intermediate changes
commit_hash:0440953ee45e859ed9f13c00cc38df246289314f
Diffstat (limited to 'library/python')
-rw-r--r-- | library/python/fs/__init__.py | 19 | ||||
-rw-r--r-- | library/python/fs/test/test_fs.py | 8 |
2 files changed, 24 insertions, 3 deletions
diff --git a/library/python/fs/__init__.py b/library/python/fs/__init__.py index 0beaf6665a6..f6bf04a7218 100644 --- a/library/python/fs/__init__.py +++ b/library/python/fs/__init__.py @@ -296,12 +296,27 @@ def copy_tree(src, dst, copy_function=shutil.copy2): # File read # Throws OSError @errorfix_win -def read_file(path, binary=True): +def read_file(path, binary=True, size=-1): + """ + Read file contents + + :param path: + File path + + :param binary: + If `True`, read in binary mode. Read in text mode otherwise. + + :param size: + An optional numeric argument. + When size is omitted or negative, the entire contents of the file will be read and returned; + it’s your problem if the file is twice as large as your machine’s memory. + Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. + """ kwargs = {} if not binary and six.PY3: kwargs['encoding'] = sys.getfilesystemencoding() with open(path, 'r' + ('b' if binary else ''), **kwargs) as f: - return f.read() + return f.read(size) # Text file read diff --git a/library/python/fs/test/test_fs.py b/library/python/fs/test/test_fs.py index 9e2c70c0690..066c0237a4a 100644 --- a/library/python/fs/test/test_fs.py +++ b/library/python/fs/test/test_fs.py @@ -808,6 +808,10 @@ def test_read_file(path): mkfile(path('src'), 'SRC') assert library.python.fs.read_file(path('src')).decode(library.python.strings.fs_encoding()) == 'SRC' assert library.python.fs.read_file(path('src'), binary=False) == 'SRC' + # test size + assert library.python.fs.read_file(path('src'), size=2, binary=False) == 'SR' + assert library.python.fs.read_file(path('src'), size=100, binary=False) == 'SRC' + assert library.python.fs.read_file(path('src'), size=-1, binary=False) == 'SRC' @in_env @@ -1023,7 +1027,9 @@ def test_copy2(): def test_commonpath(): pj = os.path.join - pja = lambda *x: os.path.abspath(pj(*x)) + + def pja(*x): + return os.path.abspath(pj(*x)) assert library.python.fs.commonpath(['a', 'b']) == '' assert library.python.fs.commonpath([pj('t', '1')]) == pj('t', '1') |