Skip to content

Commit

Permalink
✨ force read a physical file as a different format, which then will s…
Browse files Browse the repository at this point in the history
…elects a particular reader. for example: force txt file as csv. But forcing xls as xlsx may not give you any benefit, because pyexcel-xls reads both xls and xlsx. related to: pyexcel/pyexcel#148
  • Loading branch information
chfw committed Aug 23, 2018
1 parent bc921f6 commit 574b892
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
17 changes: 13 additions & 4 deletions pyexcel_io/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ def iget_data(afile, file_type=None, **keywords):
:param sheet_index: the index of the sheet to be loaded
:param sheets: a list of sheet to be loaded
:param file_type: used only when filename is not a physial file name
:param force_file_type: used only when filename refers to a physical file
and it is intended to open it as forced file type.
:param streaming: toggles the type of returned data. The values of the
returned dictionary remain as generator if it is set
to True. Default is False.
Expand Down Expand Up @@ -147,6 +149,7 @@ def load_data(
file_content=None,
file_stream=None,
file_type=None,
force_file_type=None,
sheet_name=None,
sheet_index=None,
sheets=None,
Expand All @@ -158,6 +161,8 @@ def load_data(
:param filename: actual file name, a file stream or actual content
:param file_type: used only when filename is not a physial file name
:param force_file_type: used only when filename refers to a physical file
and it is intended to open it as forced file type.
:param sheet_name: the name of the sheet to be loaded
:param sheet_index: the index of the sheet to be loaded
:param keywords: any other parameters
Expand All @@ -169,10 +174,14 @@ def load_data(
raise IOError(constants.MESSAGE_ERROR_02)

if file_type is None:
try:
file_type = file_name.split(".")[-1]
except AttributeError:
raise Exception("file_name should be a string type")
if force_file_type:
file_type = force_file_type
else:
try:
file_type = file_name.split(".")[-1]
except AttributeError:
raise Exception(
"file_name should be a string type")

reader = READERS.get_a_plugin(file_type, library)
if file_name:
Expand Down
10 changes: 10 additions & 0 deletions tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@
PY2 = sys.version_info[0] == 2


def test_force_file_type():
test_file = "force_file_type.txt"
data = get_data(
os.path.join("tests", "fixtures", test_file),
force_file_type="csv"
)
expected = [[1, 2, 3]]
eq_(expected, data[test_file])


@raises(IOError)
def test_no_valid_parameters():
load_data()
Expand Down

0 comments on commit 574b892

Please sign in to comment.