gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:28:17 25 4
gpt4 key购买 nike

假设我有一个文件名 (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 .

关于python - 读取文件并将值存储到python中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18412179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com