【发布时间】:2019-03-17 06:04:13
【问题描述】:
我知道我可以读取文件 (file.txt),然后将每一行用作变量的一部分。
f = open( "file.txt", "r" )
for line in f:
sentence = "The line is: " + line
print (sentence)
f.close()
但是,假设我有一个包含以下行的文件:
joe 123
mary 321
dave 432
在 bash 中,我可以执行以下操作:
cat file.txt | while read name value
do
echo "The name is $name and the value is $value"
done
如何用 Python 做到这一点?换句话说,每行中的每个“单词”都将它们读取为变量?
提前谢谢你!
【问题讨论】:
-
"joe 123".split()是一个列表["joe", "123"]。
标签: python python-3.x file variables