Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file and storing values into variables in python

Let's say I have a filename (test.txt) with the following data in it:

AA11 BB11 CC11 DD11
AA22 BB22 CC22 DD22
AA33 BB44 CC44 DD33

in bash (shell scripting) I can do the following:

cat test.txt | while read a b c d 
do
echo "this is the first column $a "
echo "this is the second column $b "
echo "this is the third column $c "
echo "this is the fifth column $d "
done

How can I do the same with python? how can I store the value of each column in a variable and then read the file line by line while storing and manipulating their value?

like image 775
Omar Santos Avatar asked Feb 22 '26 01:02

Omar Santos


1 Answers

file = open('test.txt')
for line in file:
    fields = line.strip().split()
    print fields[0], fields[1], fields[2], fields[3]

Python is so easy :)

To be more specific, split() splits the contents of a string into fields delimited by some delimiter (by default any blank character, e.g. space, tab etc.), and returns an array with the split fields. strip() strips all blank characters from the beginning and end of a line. And a file in python is an iterable object which when iterated over by the keyword in, gives the lines in the file one by one. For more information on these, you can look at 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 .

like image 156
Subhasis Das Avatar answered Feb 23 '26 13:02

Subhasis Das



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!