假设我有一个文件名(test.txt),其中包含以下数据:
AA11 BB11 CC11 DD11
AA22 BB22 CC22 DD22
AA33 BB44 CC44 DD33
在bash(shell脚本)中,我可以执行以下操作:
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
我怎样才能对python做同样的事情呢?如何将每个列的值存储在变量中,然后在存储和操作它们的值时逐行读取文件?
现在,每个
col
都有四列中每个列的所有条目Python很简单:)
更具体地说,
split()
将字符串的内容拆分为由某个分隔符分隔的字段(默认情况下为任何空白字符,例如空格、制表符等),并返回包含拆分字段的数组。strip()
从行首和行尾删除所有空白字符。python中的文件是一个iterable
对象,当用关键字in
进行迭代时,该对象会逐个给出文件中的行。有关这些的详细信息,可以查看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。subbasis-Das在文件打开、拆分等方面的回答很好。 但是你想要有值变量。那也很容易。而不是
写
但是,对于多于或少于四列的行,这将引发异常。
相关问题 更多 >
编程相关推荐