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

add file writing and reading routines, v2.7.39

parent 99cdd5ba
No related branches found
No related tags found
No related merge requests found
......@@ -2,3 +2,4 @@
* added `postcondition`
* added __slots__ to `ReprableMixin` and `Multirun`
* added `read_in_file` and `write_to_file`
......@@ -15,3 +15,13 @@ split
-----
.. autofuction:: satella.files.split
read_in_file
------------
.. autofunction:: satella.files.read_in_file
write_to_file
-------------
.. autofunction:: satella.files.write_to_file
__version__ = '2.7.39_a7'
__version__ = '2.7.39'
import typing as tp
import re
import os
__all__ = ['read_re_sub_and_write', 'find_files', 'split']
import codecs
__all__ = ['read_re_sub_and_write', 'find_files', 'split', 'read_in_file', 'write_to_file']
SEPARATORS = {'\\', '/'}
SEPARATORS.add(os.path.sep)
......@@ -29,6 +31,41 @@ def split(path: str) -> tp.List[str]:
return data
def write_to_file(path: str, data: tp.Union[bytes, str], encoding: tp.Optional[str] = None) -> None:
"""
Write provided content as a file, applying given encoding (or data is bytes, if none given)
:param path: Path to put the file under
:param data: Data to write. Must be bytes if no encoding is given, str otherwise
:param encoding: Encoding. Default is None, which means no encoding (bytes will be written)
"""
if encoding is None:
file = open(path, 'wb')
else:
file = codecs.open(path, 'wb', encoding)
try:
file.write(data)
finally:
file.close()
def read_in_file(path: str, encoding: tp.Optional[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.
"""
if encoding is None:
file = open(path, 'rb')
else:
file = codecs.open(path, 'rb', encoding)
try:
return file.read()
finally:
file.close()
def read_re_sub_and_write(path: str, pattern: tp.Union[re.compile, str],
repl: tp.Union[tp.Callable[[tp.Any], str]]) -> None:
"""
......
......@@ -3,7 +3,7 @@ from os.path import join
import tempfile
import unittest
import shutil
from satella.files import read_re_sub_and_write, find_files, split
from satella.files import read_re_sub_and_write, find_files, split, read_in_file, write_to_file
def putfile(path: str) -> None:
......@@ -12,6 +12,13 @@ def putfile(path: str) -> None:
class TestFiles(unittest.TestCase):
def test_read_in_and_write_to(self):
data = 'żażółć gęślą jaźń'
write_to_file('temp.tmp', data, 'UTF-8')
data2 = read_in_file('temp.tmp', 'UTF-8')
self.assertEqual(data, data2)
def test_split(self):
self.assertIn(split('c:/windows/system32/system32.exe'), [['c:', 'windows', 'system32',
'system32.exe'],
......
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