Python中的Readlines方法跳过文件标题后的第一行

Python中的Readlines方法跳过文件标题后的第一行,python,readlines,Python,Readlines,文件内部的结构是 filename = os.path.abspath(r'C:\x\y\Any.ini') #Using absolute path file = (open(filename, 'r', encoding='UTF-8')) for line in file: if ("Heading A") in line: for line in file: out = file.readlines()[1:]

文件内部的结构是

filename = os.path.abspath(r'C:\x\y\Any.ini') #Using absolute path
file = (open(filename, 'r', encoding='UTF-8'))
for line in file:
    if ("Heading A") in line:
        for line in file:
            out = file.readlines()[1:]
                    print(out)
我也试过了

[Heading A] #I don't want to read 
a[0]    # Not being read although i want to
a[1]    # Starts to be read in the program
b 
c
现在我从[1]上得到了指纹。始终跳过[0]


在继续阅读文件第2行时,我是否遗漏了任何内容

您有一个健全的配置文件。阅读以下内容

file.read().splitlines()
试试这个:

https://docs.python.org/3/library/configparser.html

以下方法可能有效

firstLine = file.readline()
    if firstLine.startsWith("[Heading A]"):
        for line in file:
            //code

要添加一些解释:

有关逐行读取文件的信息,请参见

您的问题是,您正在使用多个调用,每个调用从文件中读取一行或多行,而下一个读取调用中该行已消失-请参阅代码中的我的注释:

filename = os.path.abspath(r'C:\x\y\Any.ini') #Using absolute path
file_lines = open(filename, 'r', encoding='UTF-8').readlines()[1:]
for line in file_lines:
    print(line)
您要做的是逐行阅读并删除包含
标题A

for line in file: // reads the first line and would read again if we came back here before the end of the file, which we do not
if ("Heading A") in line:
    for line in file: // reads the second line of the file and would read again if we came back here before the end of the file, which we do not
        out = file.readlines()[1:] // reads all remaining lines from the file ( beginning from the third) and drops the first (line three in the file) by indexing [1:]
                print(out) // prints out all lines begining with the fourth; after this, the file is at its and and both for loops will be finished

这是因为读取指针(或特定的流位置)在您遍历文件时前进。在您的情况下,两个
for
循环将对此负责。在第二个循环中调用
readlines()
时,它只循环文件中的其余行,因此看起来好像在跳过行

既然你想读“标题A”后面的行,你只要一遇到它就可以读所有的行。同样的代码应该如下所示:

filename = os.path.abspath(r'C:\x\y\Any.ini') #Using absolute path
file = (open(filename, 'r', encoding='UTF-8'))
for line in file:
    if not ("Heading A") in line: print (line)

当您将
file.readlines()[1:
更改为
file.readlines()
file.readlines()[1:]从b和从a[1]分别得到文件.readlines()时,您得到了什么
filename = os.path.abspath(r'C:\x\y\Any.ini')
file = (open(filename, 'r', encoding='UTF-8'))
for line in file:
    if ("Heading A") in line:
        out = file.readlines()[
        print(out)