读取文件并将值存储到python中的变量中 [英] Reading a file and storing values into variables in python
问题描述
假设我有一个文件名(test.txt),其中包含以下数据:
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
在bash(shell脚本)中,我可以执行以下操作:
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
我该如何使用python做同样的事情?如何将每列的值存储在变量中,然后在存储和操作它们的值时逐行读取文件?
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?
推荐答案
file = open('test.txt')
for line in file:
fields = line.strip().split()
print fields[0], fields[1], fields[2], fields[3]
Python非常简单:)
Python is so easy :)
更具体地说, split()
将字符串的内容拆分为由某些定界符(默认情况下为任何空白字符,例如空格,制表符等)定界的字段,并返回包含以下内容的数组:拆分字段. strip()
从行的开头和结尾去除所有空白字符.python中的文件是一个 iterable
对象,当使用关键字 in
进行迭代时,该对象逐行给出文件中的行.有关这些的更多信息,请查看 http://docs.python.org/2/library/stdtypes.html#str.split , http://docs.python.org/2/library/stdtypes.html#bltin-file-objects .
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 .
这篇关于读取文件并将值存储到python中的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!