阅读文本文档中的下一行

2024-09-26 22:51:37 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我想给学校的项目做一个实时信息屏幕, 我在读一个文件,它做了很多不同的事情,这取决于它读的是哪一行。你知道吗

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'属性

`


Tags: infordbdataiflineitemsall
2条回答

^{}应该在文件对象上调用(在本例中是f),而不是在字符串上调用(line)。你知道吗

Python知道f的当前位置,因此f.next()将自动读取line后面的行。你知道吗

请注意,这将影响for line in f循环:此循环将每隔一行跳过f.next()返回的那一行。你知道吗

使用此test.txt文件:

1
2
3
4
5
6

此代码:

with open('test.txt') as file:
    for line in file:
        print line, file.next()

退货:

1
2

3
4

5
6

如果这不是您想要的行为,您可以看看这个thread.

可以在助手字符串中保留上一行。(注意,我使用的是上一个/current,而不是current/next)

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+')
    currLine = f.readline()
    while line != '':
        prevLine = currLine
        currLine = f.readline()
        if 'interface Vlan' in prevLine :
            interface = re.search(r'(?<=\interface Vlan).*', line).group(0)

        if 'vrf member' in currLine:
            vrfmem = interface = re.search(r'(?<=\vrf member).*', line).group(0)
        else:
            vrfmem = "default"

        if 'ip address' in prevLine:
            print(items + interface + vrfmem + "ip her" )
    db.commit()
    db.close()

相关问题 更多 >

    热门问题