Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def readTXT(loc, fileName, sep, commentChar):
- import os
- import numpy as np
- # check inputs
- check = [os.path.isdir(loc), os.path.isfile(os.path.join(loc, fileName)), os.path.splitext(fileName)[1] in [".txt", ".asc"]]
- try:
- # Open file and readlines if line does not start with commentChar
- f = open(os.path.join(loc, fileName), "r")
- lines = [line.strip('\n') for line in f.readlines() if line[0] is not commentChar]
- # placeholders for array rows and the nr. of columns in each row
- rows = []
- colLengths = []
- # Verify the number of columns in each row
- for line in lines:
- colLengths.append(len([len(i) for i in line.split(sep) if len(i) is not 0]))
- # If all rows have equal number of columns
- if len(set(colLengths)) <= 1:
- # Add each line to the rows list
- for line in lines:
- rows.append([int(i) for i in line.split(sep)])
- # Vertical stack the all rows into an array
- out = np.vstack(tuple(rows))
- else:
- raise ValueError("Number of columns is not equal over the input array: {0}".format(colLengths))
- return out
- except (RuntimeError, IOError) as e:
- print "Something went wrong, check the following: {0}".format(zip(["Valid Directory?", "Valid filename?", "Valid file extension?"], check))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement