你好,我想给学校的项目做一个实时信息屏幕, 我在读一个文件,它做了很多不同的事情,这取决于它读的是哪一行。你知道吗
dclist = []
interface = ""
vrfmem = ""
db = sqlite3.connect('data/main.db')
cursor = db.cursor()
cursor.execute('''SELECT r1 FROM routers''')
all_rows = cursor.fetchall()
for row in all_rows:
dclist.append(row[0])
for items in dclist:
f = open('data/'+ items + '.txt', 'r+')
for line in f:
if 'interface Vlan' in line:
interface = re.search(r'(?<=\interface Vlan).*', line).group(0)
if 'vrf member' in line.next():
vrfmem = interface = re.search(r'(?<=\vrf member).*', line).group(0)
else:
vrfmem = "default"
if 'ip address' in line:
print(items + interface + vrfmem + "ip her" )
db.commit()
db.close()
如代码所示,文档中的每一行我都要检查下一行,因为如果它与某个字符串匹配,我就设置一个变量。你知道吗
据我所知,python有一个内置函数next(),支持我完成这项工作。但当我运行代码时,我看到的是'AttributeError:'str'对象没有'next'属性
`
^{} 应该在文件对象上调用(在本例中是
f
),而不是在字符串上调用(line
)。你知道吗Python知道
f
的当前位置,因此f.next()
将自动读取line
后面的行。你知道吗请注意,这将影响
for line in f
循环:此循环将每隔一行跳过f.next()
返回的那一行。你知道吗使用此
test.txt
文件:此代码:
退货:
如果这不是您想要的行为,您可以看看这个thread.
可以在助手字符串中保留上一行。(注意,我使用的是上一个/current,而不是current/next)
相关问题 更多 >
编程相关推荐