python - 读取文本文件值并将其分配给变量的每个值
问题描述
我想读取文本文件并在下面的文本中找到以 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
结尾
提前致谢
解决方案
您是否尝试为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`
请注意,后者取决于文件中没有空格 - 如果文件非常大,则有点危险(您可能会遇到命令行长度限制)。
推荐阅读
- powerbi - 在 Power BI 中多次出现相同排名的排名后添加等号(例如 1= 和 9=)
- terminal - 使用 Ctrl+Click 从 linux 终端中的路径打开文件
- python - 使用 Celery 进行轮班的任务链
- c++ - 如何通过 postgres 在准备好的语句中插入时间戳?
- python - 是否有任何选项可以使用类/对象在 Python 中将 JSON 文件转换为 CSV?
- android - 在卡片视图中排列小部件
- r - XML 文件到数据框
- javascript - 如何自定义 D3 图表标签
- sympy - sympy:计算多项式的 lcm() 而不扩展结果
- authentication - 如何根据请求的范围自定义 KeyCloak 身份验证流程