Advertisement
Guest User

readTXT function

a guest
Mar 31st, 2016
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. def readTXT(loc, fileName, sep, commentChar):
  2.     import os
  3.     import numpy as np
  4.  
  5.     # check inputs
  6.     check = [os.path.isdir(loc), os.path.isfile(os.path.join(loc, fileName)), os.path.splitext(fileName)[1] in [".txt", ".asc"]]
  7.     try:
  8.         # Open file and readlines if line does not start with commentChar
  9.         f = open(os.path.join(loc, fileName), "r")
  10.         lines = [line.strip('\n') for line in f.readlines() if line[0] is not commentChar]
  11.    
  12.         # placeholders for array rows and the nr. of columns in each row
  13.         rows = []
  14.         colLengths = []
  15.        
  16.         # Verify the number of columns in each row
  17.         for line in lines:
  18.             colLengths.append(len([len(i) for i in line.split(sep) if len(i) is not 0]))
  19.        
  20.         # If all rows have equal number of columns
  21.         if len(set(colLengths)) <= 1:
  22.             # Add each line to the rows list
  23.             for line in lines:
  24.                 rows.append([int(i) for i in line.split(sep)])
  25.             # Vertical stack the all rows into an array
  26.             out = np.vstack(tuple(rows))
  27.         else:
  28.             raise ValueError("Number of columns is not equal over the input array: {0}".format(colLengths))
  29.         return out
  30.        
  31.     except (RuntimeError, IOError) as e:
  32.         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