simple files

Dave Harrison dave at nullcube.com
Sat May 31 02:50:12 EDT 2003


> Hey how come when i do this it just outputs the last line and not the rest of the lines ??? I wish to output each line from file into a seperate list .....
> eg. first line ['1', 'yea', '2']
>      sec line ['3', 'hi', '4']
>
> def readtable(filename):
>    intabfile = open(filename, "r")
>    for tablines in intabfile:
>       tab = string.split(tablines, ":" ,10)
>    intabfile.close()
>    return tab

essentially what you have done is :

- open the file
- for each line of the file assign THAT line to a single variable

then print that variable, which at the end of the file will
be the last line.

What you want to do is :

def readFile(filename):
	# Declare the list to populate
	retList = []

	# Open file and create list of line, the file object
	# will pass out of scope at the end of the call and die
	myFileList = file(filename).readlines()
	
	# For each line in our file
	for line in myFileList:
		# Append the split to the list
		retList.append(string.split(line, ':', 10)

	# Now return our 2d list of line lists
	return retList





More information about the Python-list mailing list