Python 读取文件并将每一行用作变量?

Python 读取文件并将每一行用作变量?,python,python-3.x,file,variables,Python,Python 3.x,File,Variables,我知道我可以读取一个文件(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 val

我知道我可以读取一个文件(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实现这一点?换句话说,每行中的每个“单词”都将它们作为变量读取


提前谢谢你

肾盂等效物可以是:

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}')
它使用:

  • 上下文管理器(带有语句的
    ),用于在完成后自动关闭文件
  • tuple/list解包以从
    .split()返回的列表中分配
    名称
  • 新的
    f
    字符串语法具有变量插值功能。(对于较旧的python版本,请使用
    str.format

“joe 123”。split()是一个列表
[“joe”,“123”]
。你能解释一下OP为什么是他的问题的答案吗?他在文件中输入了这样的内容
joe 123\n mary 321\n dave 432
,我们阅读该文件,逐行迭代,然后拆分每行,因此值[0]将有名称和值[1]将有编号,然后相应打印。我希望这能回答你的疑问,
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()