首页 > 解决方案 > 读取文本文件值并将其分配给变量的每个值

问题描述

我想读取文本文件并在下面的文本中找到以 56 开头的单词,并将每个单词传递给一个变量并作为参数传递给一个 python 文件。

我的示例文本文件内容 -

51:40:2e:c0:01:c9:53:e8
56:c9:ce:90:4d:77:c6:03
56:c9:ce:90:4d:77:c6:07
51:40:2e:c0:01:c9:54:80
56:c9:ce:90:12:b4:19:01
56:c9:ce:90:12:b4:19:03

我喜欢传递给python文件

mytestfile.py var1 var2 var3 

var1 的值应为 56:c9:ce:90:4d:77:c6:03 var2 的值应为 56:c9:ce:90:4d:77:c6:07 var3 的值应为 56:c9:ce:90: 12:b4:19:01

很快

我写了类似下面的代码但不工作

[#var1 = "51:40:2e:c0:01:c9:53:e8"] [#var2 = "51:40:2e:c0:01:c9:53:ea"]

   filepath = '/root/SDFlex/work/cookbooks/ilorest/files/file.txt'  
       with open(filepath) as fp:  
       line = fp.readline()
       cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1

执行“运行创建卷脚本”做

    command "python SDFlexnimblevolcreate.py #{var1} #{node['ilorest']['Test0']} #{var2} #{node['ilorest']['Test1']} 
    cwd "#{platformdirectory}"
    live_stream true

结尾

提前致谢

标签: python

解决方案


您是否尝试为mytestfile.py以“56:”开头的每一行运行一次,如下所示:

python mytestfile.py 56:c9:ce:90:4d:77:c6:03
python mytestfile.py 56:c9:ce:90:4d:77:c6:07
python mytestfile.py 56:c9:ce:90:12:b4:19:01

或者您是否只想运行一次,将文件中的所有值作为参数提供,例如,使用您的示例数据:

python mytestfile.py 56:c9:ce:90:4d:77:c6:03 56:c9:ce:90:4d:77:c6:07 56:c9:ce:90:12:b4:19:01

如果是前者(每个匹配行运行一次),最简单的方法是:

grep '^56' textfile | xargs python mytestfile.py

否则,您可以这样做:

python mytestfile.py `grep '^56' textfile`

请注意,后者取决于文件中没有空格 - 如果文件非常大,则有点危险(您可能会遇到命令行长度限制)。


推荐阅读