Python script to read csv file and split onto new lines


Sam Allen has posted a good walk through here, which explains how to use Python to read a comma separated list in a text file.

Starting with a text file like this one:

. . . the file can be opened in Python and then analyzed. First the open command is used to open the file:

>>> f = open(r"C:\FooFolder\python\animals.txt", "r")

Sam's script contains a small error. The r is omitted before the file path. At least in version 3.4.2 of Python this must be included to access the file.

readlines is used to read each line in the file:

>>> for line in f.readlines():

strip is used to take out whitespace: line = line.strip()

print displays the line: print(line)

split up each line: parts = line.split(",")

display each line indented: for part in parts: print(" ", part)

The end result is:

tigers,giraffes,lions,zebra,elephants,dogs,cats,gazelles tigers giraffes lions zebra elephants dogs cats gazelles >>>

The complete script looks like this in Python IDLE


Contact Me With Your Litigation Support Questions:

seankevinoshea@hotmail.com

  • Twitter Long Shadow

© 2015 by Sean O'Shea . Proudly created with Wix.com