def txt2array(txtfile):
	"""
	txt2array(txtfile)

	Reads a file containing a text representation of a matrix (i.e. a certain number of lines each containing the same numbers separated by spaces) of any size.  Returns an array containing this data.
	"""
	
	import numpy				# Import numpy to use arrays 
	f = []					# Initiate f as a list to be read in.  At the end we will make it an array.
	try:
		file = open(txtfile, 'r')	# We will read our data from this file
	except IOError:
		print "'%s' could not be opened because the file does not exist" % txtfile
		return	
	for line in file:
		array_line = []			# Clear contents of array_line before reading in each line
		for entry in line.split():	# Allows for any number of entries in each line of the txt file
			array_line.append(float(entry))	# For each entry in the line, convert the string to a float type and append it to the list of numbers in that row  
		f.append(array_line)		# Once the contents of the line have been stored in the array_line list, add them as a new "row" to the f list-matrix
	return numpy.array(f,float)		# Return the completed 2D list as a float type array



def array2txt(TwoD_array,txt_outfile,a_or_w):
	"""
	array2txt(TwoD_array,txt_outfile,a_or_w)

	Converts a two-dimensional array of any size to a text representation of the matrix and writes this matrix to the text file specified by txt_outfile.  Use a_or_w to specify append('a') or write('w').
	"""

	import numpy				# Import numpy to use arrays
	M_rows, N_cols = TwoD_array.shape	# Extract number of rows and columns of M x N matrix
	f = TwoD_array.tolist()			# Convert the array to an M x N nested list
	file = open(txt_outfile,a_or_w)		# We will write our data to this file  ## EITHER APPENDS OR WRITES DEPENDING ON INPUT a_or_w
	for row in xrange(M_rows):		# for row indexes from 0 to (M_rows - 1):
		line = ''			# Initiate a new string for each line
		for entry in f[row]:
			line += `entry` + '\t'	# Each line should consist of entry1 + tab + entry2 + tab + ... + entryN + tab
		line += '\n'			# Create a newline at the end of each line	
		file.write(line)		# Write each line to the output file
	file.close()	

