[英]Searching a file with input from another file in python
我想做的是从一个文件到字符串读取一行,然后在另一个文件中搜索包含该字符串的行,并使用.split()
解析该行。
我的代码如下所示:
for line in portslist:
marker = line.split()
printername = marker[0]
address = marker[1]
for lines in constantfile:
if address in line: #if the desired address is in the line
lineholder = line
lineholder = lineholder.split()
oldonline = lineholder[4]
oldutc = lineholder[5]
status = lineholder[2]
但是,我得到了错误
in readermain oldonline=lineholder[4] IndexError: list index out of range
经过一些故障排除后,似乎我的constantfile中的行从未分配给line。 相反,似乎文件端口列表中的行已分配给仅索引为2的行。
我的问题是如何将字符串"address"
分配给该行,以便我可以解析和使用它?
我认为您正在使用line
,而应该使用lines
:
for lines in constantfile:
if address in lines: #if the desired address is in the line
lineholder=lines.split()
# etc.
同样,如果constantfile
是文件对象,则该迭代器将在外部for
循环的第一遍通过后耗尽。
您的缩进使得即使“行内地址”评估为假,该块的其余部分也将运行。
其次,来自constantfile的行应分配给变量“ lines”。 将相应代码改写为
if address in lines:
lineholder = lines
...
你应该很好
此外,我建议使用一种不太随意的命名约定,该约定明确表明您正在处理来自2个不同文件的行。 例如
这样,它将减少混乱,并且您的代码将更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.