【问题标题】:Reading a file and using each line as variables?读取文件并将每一行用作变量?
【发布时间】:2019-03-17 06:04:13
【问题描述】:

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

提前谢谢你!

【问题讨论】:

  • "joe 123".split() 是一个列表["joe", "123"]

标签: python python-3.x file variables


【解决方案1】:

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 字符串语法,具有变量插值功能。 (对于较旧的 Python 版本,请使用 str.format

【讨论】:

    【解决方案2】:
    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()
    

    【讨论】:

    • 你能解释一下 OP 为什么这是他问题的答案吗?
    • 他在文件中输入了这样的joe 123 \n mary 321 \n dave 432,我们读取该文件并逐行迭代然后拆分每一行,因此 values[0] 将有名称,而 values[1] 将有数字然后相应地打印。我希望这能回答您的问题,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2014-03-02
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    相关资源
    最近更新 更多