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

标签 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 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/

相关文章:

python - 如何修复 : MatplotlibDeprecationWarning: shading ='flat' when X and Y have the same dimensions as C is deprecated since 3. 3

c++ - 从文件中读取数据到结构数组 C++

java - 有没有办法检索java源文件?

java - 如何更改默认保存在 .camel 子目录中的文件的位置

python - 使用 Flask-dance 和 Google oauth 获取 'Missing required parameter: refresh_token'

python - OAuth 2.0 教程?

python - 如何从 shell 启动和停止 Python 脚本

python-3.x - 多线程 celery worker 的任务划分

python - 在 `str.format()` 中使用多个 if 条件

python-3.x - Python 3.6 模块未找到错误 : No module named 'pyttsx3'