在python中读取文件并将值存储到变量中

2024-09-29 23:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个文件名(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做同样的事情呢?如何将每个列的值存储在变量中,然后在存储和操作它们的值时逐行读取文件?


Tags: the数据testechotxtis文件名column
3条回答
with open('test.txt') as infile:
  lines = [line.strip().split() for line in infile] # bad for large files
  col1, col2, col3, col4 = itertools.izip(*lines)

现在,每个col都有四列中每个列的所有条目

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.splithttp://docs.python.org/2/library/stdtypes.html#str.striphttp://docs.python.org/2/library/stdtypes.html#bltin-file-objects

subbasis-Das在文件打开、拆分等方面的回答很好。 但是你想要有值变量。那也很容易。而不是

fields = line.strip().split()

a,b,c,d = line.strip().split()

但是,对于多于或少于四列的行,这将引发异常。

相关问题 更多 >

    热门问题