from fastcore.test import *
from unittest import mock
Files and folders
File existence
file_existence_test
file_existence_test (path:os.PathLike, relative_to:Optional[os.PathLike]=None)
*Deprecated. Use existing_path
instead.
Returns a path relative to a specified path as an absolute path that exists.
Raises - FileNotFoundError
- If relative_to
is not None
but does not exist, or if file
does not exist.
Notes - This function may add the string '\\?\'
in front, which identifies very long paths.*
Type | Default | Details | |
---|---|---|---|
path | PathLike | A file or directory path. Either absolute or relative to relative_to . |
|
relative_to | Optional | None | Path to the directory that file is relative to. If None , then path is an absolute path. |
Returns | Path | The path formed by relative_to adjoined with path . Defaults to None |
existing_path
existing_path (path:os.PathLike, relative_to:Optional[os.PathLike]=None)
*Returns a path relative to a specified path as an absolute path that exists.
Raises
FileNotFoundError
- If
relative_to
is notNone
but does not exist, or iffile
does not exist.
- If
ValueError
- If
relative_to
is notNone
and yet not an absolute path, or ifrelative_to
isNone
at yetpath
is not an absolute path.
- If
Notes - This function may add the string '\\?\'
in front, which identifies very long paths.*
Type | Default | Details | |
---|---|---|---|
path | PathLike | A file or directory path. Either absolute or relative to relative_to . |
|
relative_to | Optional | None | Path to the directory that file is relative to. If None , then path is an absolute path. |
Returns | Path | The path formed by relative_to adjoined with path . Defaults to None |
In the following example, the existing_path
method returns an existing absolute path \(p_2 \backslash p_1\) which is equivalent to a specified path \(p_1\) relative to an existing absolute path \(p_2\). Note that all paths and os
methods are mocked:
with (mock.patch('os.path.exists') as mock_path_exists,
'os.path.isabs') as mock_is_abs):
mock.patch(= True
mock_path_exists.return_value = True
mock_is_abs.return_value = existing_path('mock_existing_relative_path', 'mock_existing_absolute_path')
path_1 'mock_existing_absolute_path') / 'mock_existing_relative_path', path_1) test_eq(Path(
If the desired path is very long in Windows, then the \\?\
may be appended in front of the absolute path so that Python can actually find the path, cf. https://stackoverflow.com/questions/36219317/pathname-too-long-to-open:
# TODO provide an example
with (mock.patch('os.path.exists') as mock_path_exists,
'os.path.isabs') as mock_is_abs):
mock.patch(print('hi')
hi
If the parameter relative_to
, which is supposed to be an absolute path, is not None
and not absolute, then a ValueError
is raised:
with (ExceptionExpected(ex=ValueError, regex='absolute path'),
'os.path.exists') as mock_path_exists,
mock.patch('os.path.isabs') as mock_is_abs):
mock.patch(= False
mock_is_abs.return_value = 'mock_relative_path_that_is_not_None'
path = 'mock_non_absolute_path'
relative_to 'mock_relative_to_that_is_not_None', relative_to)
existing_path(
with (ExceptionExpected(ex=ValueError, regex='absolute path'),
'os.path.exists') as mock_path_exists,
mock.patch('os.path.isabs') as mock_is_abs):
mock.patch(= False
mock_is_abs.return_value # It does not matter what `path`` is - as long as `relative_to`` is not `None` and not absolute, the ValueError is raised.
= None
path = 'mock_non_absolute_path'
relative_to 'mock_relative_to_that_is_not_None', relative_to) existing_path(
If the parameter relative_to
is None
and the paramether path
is not absolute, then a ValueError
is raised:
with (ExceptionExpected(ex=ValueError, regex='absolute path'),
'os.path.isabs') as mock_is_abs):
mock.patch(= False
mock_is_abs.return_value = None
relative_to = 'mock_non_absolute_path'
path existing_path(path, relative_to)
If relative_to
does not exist or if path
does not exist, then a FileNotFoundError
is raised:
# In this example, both `relative_to` and `path` are specified, and `relative_to`
# is a non-existent path.`
with (ExceptionExpected(ex=FileNotFoundError),
'os.path.exists') as mock_path_exists,
mock.patch('os.path.isabs') as mock_is_abs):
mock.patch(= 'mock_non_existent_absolute_path'
relative_to = 'mock_some_relative_path'
path def relative_to_does_not_exist(path_to_check):
return False if path_to_check is relative_to else True
def relative_to_is_absolute_path(path_to_check):
return True if path_to_check is relative_to else False
= relative_to_does_not_exist
mock_path_exists.side_effect = relative_to_is_absolute_path
mock_is_abs.side_effect
existing_path(path, relative_to)
# In this example, both `relative_to` and `path` are specified, and `path`
# is a non-existent path.`, whereas `relative_to` exists.
with (ExceptionExpected(ex=FileNotFoundError),
'os.path.exists') as mock_path_exists,
mock.patch('os.path.isabs') as mock_is_abs):
mock.patch(= 'mock_existent_absolute_path'
relative_to = 'mock_non_existent_relative_path'
path def only_relative_to_exists(path_to_check):
# only `relative_to` exists; all other paths of interest do not exist.
return path_to_check is relative_to
def relative_to_is_absolute_path(path_to_check):
return True if path_to_check is relative_to else False
= only_relative_to_exists
mock_path_exists.side_effect = relative_to_is_absolute_path
mock_is_abs.side_effect existing_path(path, relative_to)
Paths without extensions
path_name_no_ext
path_name_no_ext (path:os.PathLike)
*Return the name of a file or directory from its path without the extension.
The file or directory does not have to exist.*
Type | Details | |
---|---|---|
path | PathLike | The path of the file or directory. This may be absolute or relative to any directory. |
Returns | str | The name of the file or directory without the extension. |
Basic usage:
= Path('hypothetical_directory')
path / 'hypothetical_subdirectory'), 'hypothetical_subdirectory')
test_eq(path_name_no_ext(path / 'hypotehtical_subdirectory' / 'hypothetical_file.md'), 'hypothetical_file') test_eq(path_name_no_ext(path
The path does not have to exist.
/ 'this_folder_does_not_exist'), 'this_folder_does_not_exist') test_eq(path_name_no_ext(path
On paths to files with “multiple extensions”, the function returns the file name without the last extension only.
'archived_file_somewhere.7z.zip.tar'), 'archived_file_somewhere.7z.zip') test_eq(path_name_no_ext(
path_no_ext
path_no_ext (path:os.PathLike)
*Returns the path of a file or directory without the extension.
The file or directory does not have to exist.*
Type | Details | |
---|---|---|
path | PathLike | The path of the file or directory. This may be absolute or relative to any directory. |
Returns | str | The path of the file or directory without the extension. If path is a path to a directory, then the output should be essentially the same as path . |
Basic usage - the path does not have to exist:
assert path_no_ext('C:\\hi') == 'C:\\hi'
assert path_no_ext('greetings\\file.txt') == 'greetings\\file'
Read text from file
text_from_file
text_from_file (path:os.PathLike, encoding:str='utf8')
*Return the entire text from a file.
Assuems that the file can be encoded in the specified encoding
*
Type | Default | Details | |
---|---|---|---|
path | PathLike | The absolute path of the file. | |
encoding | str | utf8 | The encoding of the file to be read. Defaults to 'utf8' . |
Returns | str | The entire text from a file |
The text_from_file
method is a quick method to extract the text from a file.
# TODO: examples/tests
File extension
files_of_format_sorted
files_of_format_sorted (directory:os.PathLike, extension:str='txt')
Return a list of path str of files in the directory (but not subdirectories) sorted via natsort
.
Type | Default | Details | |
---|---|---|---|
directory | PathLike | The directory in which to find the files | |
extension | str | txt | Extension of the files to find. Defaults to ‘txt’. |
Returns | list |
In the following example, we mock a folder with numbered files. files_of_format_sorted
returns them in the “natural” order.
with (mock.patch('glob.glob') as mock_glob):
= Path('some_directory')
mock_directory # `glob_results`` is not sorted in "natural" order.
= [mock_directory / f'{i}.txt' for i in range (10,0, -1)]
glob_results = glob_results
mock_glob.return_value
# mock to make sure that natsorted was called.
with mock.patch(__name__ + '.natsorted') as mock_natsorted:
= files_of_format_sorted(mock_directory)
mock_files
mock_natsorted.assert_called_with(mock_glob.return_value)
# Now print out that the files are sorted in "natural" order.
= files_of_format_sorted(mock_directory)
mock_files print(mock_files)
test_shuffled(glob_results, mock_files)
[WindowsPath('some_directory/1.txt'), WindowsPath('some_directory/2.txt'), WindowsPath('some_directory/3.txt'), WindowsPath('some_directory/4.txt'), WindowsPath('some_directory/5.txt'), WindowsPath('some_directory/6.txt'), WindowsPath('some_directory/7.txt'), WindowsPath('some_directory/8.txt'), WindowsPath('some_directory/9.txt'), WindowsPath('some_directory/10.txt')]
Compressed files
file_is_compressed
file_is_compressed (filename:str)
assert file_is_compressed('asdf.tar')
assert file_is_compressed('asdf.tar.gz')
assert file_is_compressed('./hi/asdf.tar.gz')
assert not file_is_compressed('./hi/bye')
assert not file_is_compressed('./hi/bye.pdf')
uncompress_file
uncompress_file (file_path:os.PathLike, verbose:bool=False)
# TODO : test
# Example usage
# file_to_uncompress = './1605.08386v1.Heat_bath_random_walks_with_Markov_bases.tar' # Replace with your file name
# hi = uncompress_file(file_to_uncompress)
# hi
Downloads folder
get_download_path
get_download_path ()
Return the user’s download folder
HuggingFace cache
get_huggingface_cache_dir
get_huggingface_cache_dir ()
# get_huggingface_cache_dir()