0

I write function operates with some data. I start from reading data from file, put it into structure and then do some calculations. My problem - incoming file can be txt, csv or xls (xlsx). For different types of file I need to use different methods.

So, my question is - how to check the type of incoming file.

Now I use the next approach:

def main(filename):
    if '.txt' in filename:
        # use read_txt
    elif '.xls' in filename:
        print('there is no txt method')
    else:
        print('etc.')

But it is not perfect: for example if I create file My.txt.xls it fails. I think about try and use all the reading functions one by one, but look like there is some more obvious way...

Mikhail_Sam
  • 10,602
  • 11
  • 66
  • 102
  • Although the question is old, the GitHub referenced has been updated in the last month. https://stackoverflow.com/questions/10937350/how-to-check-type-of-files-without-extensions-in-python. So, I think it is still valid. – Nick Dec 27 '17 at 10:04
  • @Nick I didn't get it - your link put me on my own question. – Mikhail_Sam Dec 27 '17 at 10:06
  • Ooops! I've updated the comment. Sorry! – Nick Dec 27 '17 at 10:09

0 Answers0