在python中读取文件并将值存储到变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18412179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a file and storing values into variables in python
提问by Omar Santos
Let's say I have a filename (test.txt) with the following data in it:
假设我有一个文件名 (test.txt),其中包含以下数据:
AA11 BB11 CC11 DD11
AA22 BB22 CC22 DD22
AA33 BB44 CC44 DD33
in bash (shell scripting) I can do the following:
在 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
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?
我怎么能用python做同样的事情?如何将每列的值存储在变量中,然后在存储和操作它们的值时逐行读取文件?
采纳答案by Subhasis Das
file = open('test.txt')
for line in file:
fields = line.strip().split()
print fields[0], fields[1], fields[2], fields[3]
Python is so easy :)
Python是如此简单:)
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.
更具体地说,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。
回答by inspectorG4dget
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)
Now, each of the col
s has all the entries for each of the four columns
现在,每个col
s 都有四列中每一列的所有条目
回答by alecxe
Using csv
module:
使用csv
模块:
import csv
nth = {
1: "first",
2: "second",
3: "third",
4: "fourth"
}
with open('test.txt', 'r') as f:
reader = csv.reader(f, delimiter=" ")
for row in reader:
for index, item in enumerate(row):
print "this is the %s column %s" % (nth[index + 1], item)
And, the same without using csv
:
而且,不使用相同csv
:
nth = {
1: "first",
2: "second",
3: "third",
4: "fourth"
}
with open('test.txt', 'r') as f:
for row in f:
for index, item in enumerate(row.split()):
print "this is the %s column %s" % (nth[index + 1], item.strip())
prints:
印刷:
this is the first column AA11
this is the second column BB11
this is the third column CC11
this is the fourth column DD11
this is the first column AA22
this is the second column BB22
this is the third column CC22
this is the fourth column DD22
this is the first column AA33
this is the second column BB44
this is the third column CC44
this is the fourth column DD33
回答by Sebastian
The answer of Subhasis Das is fine regarding the file opening, splitting and so on. But you wanted to have the values variables. That's easy, too. Instead of
Subhasis Das 的答案在文件打开、拆分等方面都很好。但是您想要拥有 values 变量。这也很容易。代替
fields = line.strip().split()
write
写
a,b,c,d = line.strip().split()
For lines with more or less than four columns, this will throw an exception, though.
但是,对于多于或少于四列的行,这将引发异常。