繁体   English   中英

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

[英]Readlines method in Python skipping the first line in a file after heading

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

我也尝试过

file.read().splitlines()

现在我正在从a [1]获取打印件。 a [0]总是被跳过。

有什么我想要继续从文件第二行读取的东西吗

尝试这个:

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

您有一个理智的配置文件。 阅读以下;

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

以下可能有效。

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)

要添加一些说明:

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

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

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

您想要做的是逐行阅读并删除包含Heading 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)

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

由于您要阅读“标题A”后的行,因此遇到后只需阅读所有行即可。 相同的代码应类似于:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM