Reading text (ascii) files

For a simple file (file.txt)…

colA,colB
324,234
346,341
147,346
234,567
368,405
344,643
235,235
236,567

Method 1: Open the whole file as one big string.

f = open('file.txt', 'r') # 'r' = read
lines = f.read()
print lines,
f.close()

Alternatively, file can be read into a numpy array for easy plotting

import numpy as np
f = open('file.txt', 'r')
data = np.genfromtxt(f, delimiter=',')
delete(data,0,0) # Erases the first row (i.e. the header)
plot(data[:,0],data[:,1],'o')
f.close()

scatter_plot


Method 2: Open the whole file at once as a list of lines (i.e. each element in list = one line of the file).

f = open('file.txt', 'r') # 'r' = read
lines = f.readlines()
print lines,
f.close()

Method 3: Open a file “line-by-line”. This method doesn’t use a lot of memory (one line’s worth of memory at any given time), so it is good for really large files.

f = open('file.txt', 'r') # 'r' = read
for line in f:
  print line, # note, coma erases the "cartridge return"
f.close()
Advertisements

3 thoughts on “Reading text (ascii) files

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s