Tuesday, July 9, 2013

Read in file by command line argument and split on tab delimiter in Python

An example of how to read a file into a list based on a command line argument and split on a tab delimiter on Python with some error catching.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys

try:
    li_tsv = [line.strip() for line in open(sys.argv[1])]  # Open target file, strip newline characters from lines, define as list.
    li_tsv = [element.split('\t') for element in li_tsv]  # Split elements of list based on tab delimiters.
except IndexError:  # Check if arguments were given
    sys.stdout.write("No arguments received. Please check your input:\n")
    sys.stdout.write("\t$ python.py input.tsv\n")
    sys.exit()
except IOError:  # Check if file is unabled to be opened.
    sys.stdout.write("Cannot open target file. Please check your input:\n")
    sys.stdout.write("\t$ python.py input.tsv\n")
    sys.exit()

No comments:

Post a Comment