假设我有一个文件名(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 做同样的事情?如何将每列的值存储在变量中,然后在存储和操作它们的值时逐行读取文件?
file = open('test.txt')
for line in file:
fields = line.strip().split()
print fields[0], fields[1], fields[2], fields[3]
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 .
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)