ohm*_*hmr 2 python variables file python-3.x
我知道我可以读取文件(file.txt)然后使用每一行作为变量的一部分.
f = open( "file.txt", "r" )
for line in f:
sentence = "The line is: " + line
print (sentence)
f.close()
Run Code Online (Sandbox Code Playgroud)
但是,假设我有一个包含以下行的文件:
joe 123
mary 321
dave 432
Run Code Online (Sandbox Code Playgroud)
在bash我可以做类似的事情:
cat file.txt | while read name value
do
echo "The name is $name and the value is $value"
done
Run Code Online (Sandbox Code Playgroud)
我怎么能用Python做到这一点?换句话说,每行中的每个"单词"都将它们读作变量?
先感谢您!
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}')
Run Code Online (Sandbox Code Playgroud)
这用于:
with语句),用于在完成后自动关闭文件name和value从中返回的列表.split()f具有变量插值功能的新字符串语法.(str.format用于较旧的python版本)