[英]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.