我想创建一个只在某些点读取文本行的函数。例如,我要阅读的文件名为" text.txt"。
假设text.txt有以下5行
X This is 1st line
X This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
我希望该函数能够打印所有不以X开头的行。 到目前为止,这是我的尝试,但出于某种原因,它不会打印任何内容。
infile = open("text.txt", "r")
line = infile.readline()
while line != '':
if 'X' not in line:
line = infile.readline()
print(line)
但是,如果text.txt排列如下:
This is 1st line
This is 2nd line
This is 3rd line
X This is 4th line
X This is 5th line
答案 0 :(得分:0)
你的逻辑错误:
尝试:
if 'X' not in line:
print(line)
line = infile.readline()
答案 1 :(得分:0)
您应该使用for
- 循环来浏览整个文件:
for line in open('test.txt'):
if line[0] != 'X':
if line[-1] == "\n":
print(line[:-1])
else:
print(line)
你的基本问题是,如果' X'该行中 ,您忘记更新该行,因此会不断检查,检查和检查。 (换句话说,我认为你的代码有一个无限循环。)