我知道我可以读取文件(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做到这一点?换句话说,每一行中的每个“单词”都将它们读为变量吗?
提前谢谢!
答案 0 :(得分:6)
等效的pythonic可能是:
with open( "file.txt", "r" ) as f:
for line in f:
name, value = line.split()
print(f'The name is {name} and the value is {value}')
这使用:
with
语句),用于在完成后自动关闭文件name
返回的列表中,从value
和.split()
f
字符串语法,具有变量插值功能。 (将str.format
用于较早的python版本)答案 1 :(得分:0)
f = open( "file.txt", "r" )
for line in f:
values = line.split()
sentence = "The name is " + values[0] + " and the value is " + values[1]
print (sentence)
f.close()