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]总是被跳过。
有什么我想要继续从文件第二行读取的东西吗?
答案 0 :(得分:1)
尝试:
firstLine = file.readline()
if firstLine.startsWith("[Heading A]"):
for line in file:
//code
答案 1 :(得分:0)
您有一个理智的配置文件。阅读以下内容;
https://docs.python.org/3/library/configparser.html
答案 2 :(得分:0)
以下可能有效。
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)
答案 3 :(得分:0)
要添加一些说明:
要逐行读取文件,请参阅here。
您的问题是您正在使用多个调用,每个调用都从文件中读取一行或多行,而该行在下一次阅读调用时就消失了-请参阅代码中的注释:
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)
答案 4 :(得分:0)
这是因为在遍历文件时,读指针(或特定的流位置)前进。您的情况是,两个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)