bash - Reading a file and storing values into variables in python -
let's have filename (test.txt) following data in it:
aa11 bb11 cc11 dd11 aa22 bb22 cc22 dd22 aa33 bb44 cc44 dd33
in bash (shell scripting) can following:
cat test.txt | while read b c d echo "this first column $a " echo "this second column $b " echo "this third column $c " echo "this fifth column $d " done
how can same python? how can store value of each column in variable , read file line line while storing , manipulating value?
file = open('test.txt') line in file: fields = line.strip().split() print fields[0], fields[1], fields[2], fields[3]
python easy :)
to more specific, split()
splits contents of string fields delimited delimiter (by default blank character, e.g. space, tab etc.), , returns array split fields. strip()
strips blank characters beginning , end of line. , file in python iterable
object when iterated on keyword in
, gives lines in file 1 one. more information on these, can @ http://docs.python.org/2/library/stdtypes.html#str.split , http://docs.python.org/2/library/stdtypes.html#str.strip , http://docs.python.org/2/library/stdtypes.html#bltin-file-objects .
Comments
Post a Comment