Skip to main content

10.6) Splitting Lines


Splitting lines into words or individual components is done with the split() method.

fid=open('file.txt', 'r')
for line in fid:
    words = line.split()
    print words
fid.close()

Try the example above and check that you understand what type the object words is.

By default split() splits words separated by spaces. You can also split at commas if you are reading a comma separated value file (.csv) with split(',') or split at tabs split('\t') or colons split(':').

In following sections, we’ll learn an easier way to read csv or tab files with Numpy.