gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:57:34 24 4
gpt4 key购买 nike

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

提前致谢!

最佳答案

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 语句),用于在您完成后自动关闭文件
  • 元组/列表解包以从 .split() 返回的列表中分配 namevalue
  • 新的 f 字符串语法,具有变量插值功能。 (使用 str.format 用于较旧的 python 版本)

关于python - 读取文件并将每一行用作变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52772205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com